Facing an obstacle in Angular as I am unable to view my data

How can I bind the model of my controller in the init function and see the data when the init is called?

Index.html
 <!DOCTYPE html>
 <html ng-app="I-Sign">
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name="viewport" content="width=device-width" />
<title>Sign Language Application</title>

<link rel="stylesheet" href="scripts/jquery.mobile-1.4.5.css" />

<script type="text/javascript" charset="utf-8" src="scripts/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/angular.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/lodash.js"></script>
<script src="mainController.js"></script>
 </head>

 <body>
 <div ng-controller="MainCtrl as ctrl" ng-init="init()">

    <div id="categories">
           <ul data-role="listview" data-inset="true">
              <li ng-repeat="category in ctrl.data.categories"><a ng-     click="ctrl.showWords(category)" href="#">
                     <img src="images/Can_I.png">
                     <h1>{{category.name}}</h1>
            </a>   
            </li>
</ul>
</div>
<div id="words">
        <ul data-role="listview" data-inset="true">
                
            <li ng-repeat="word in ctrl.currentWords"><a ng-click="ctrl.showMovie()" href="#">
                     <img src="images/Can_I.png">
                     <h1>{{word.name}}</h1>
            </a>                        
            </li>
</ul>
    <div>
        <input  id="upBtn" class="ui-block-a" type="button" value="UP" ng-hide ng-click="ctrl.showCategories()">
    </div>
</div>

mainController.js

 var myApp = angular.module('I-Sign',[]);

 myApp.controller('MainCtrl', ['$scope', function($scope) {
    var self = $scope;

    $scope.init = function () {
         var that = this;
         that.getData();
         self.currentWords = [];
    }

    $scope.$watchCollection(function () {
       //var that = this;
       return self.data;
    }, function () {
        console.log("Changed");
    });

    $scope.getData = function () {
        var that = this;
         $.getJSON('data/database.json', function (data) {
            that.data = data;
        });
    }

    $scope.showCategories = function () {
         var that = this;

        $("#words").addClass("ng-hide");
        $("#categories").removeClass("ng-hide");
        $("#upBtn").assClass("ng-hide");

    }

    $scope.showWords = function (category) {
         var that = this;

        that.currentWords = [];
        $("#categories").addClass("ng-hide");
        $("#words").removeClass("ng-hide");
        $("#upBtn").removeClass("ng-hide");
        that.data.words.forEach(function (word) {
            if (word.categoryId === category.id) {
                that.currentWords.push(word);
            }
        });
    }
 }]);

Answer №1

In order to correctly handle the data fetched using jQuery, it is important to trigger .$apply() since the code execution is outside of Angular's scope.

    $.getJSON('data/database.json', function (data) {
        that.data = data;
        $scope.$apply();
    });

Alternatively, instead of relying on jQuery, consider utilizing $http by injecting it (similarly to how you injected $scope) and perform the request like this:

    $http.get('data/database.json')
        .success(function(data){
            that.data = data;
        });

Answer №2

Make sure to also modify the following:

$scope.displayCategories = function () {
     $scope.showCategories = true;
}

$scope.displayWords = function (category) {
    that.currentWords = [];
     $scope.showCategories = false;
    that.data.words.forEach(function (word) {
        if (word.categoryId === category.id) {
            that.currentWords.push(word);
        }
    });
}

and update your html code as follows:

 <div id="categories"  ng-show="showCategories">
       <ul data-role="listview" data-inset="true">
          <li ng-repeat="category in ctrl.data.categories">
                <a ng-click="ctrl.displayWords(category)" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{category.name}}</h1>
                </a>   
              </li>
          </ul>
 </div>
 <div id="words" ng-show="!showCategories">
            <ul data-role="listview" data-inset="true">                
                <li ng-repeat="word in ctrl.currentWords">
                   <a ng-click="ctrl.showMovie()" href="#">
                       <img src="images/Can_I.png">
                       <h1>{{word.name}}</h1>
                   </a>                        
                </li>
            </ul>
  </div>
  <div>
          <input  id="upBtn" class="ui-block-a" type="button" value="UP" ng-show="!showCategories" ng-click="ctrl.displayCategories()">
  </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing React Js to fail loading css when switching from anchor tag to link tag?

I am learning React and experimenting with creating a basic static website using HTML templates in version ^18.2.0 of React JS. Everything seems to be functioning correctly, however, I have encountered an issue with page refresh. Specifically, when I repla ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

The reason why setting height to 0 is ineffective in a CSS definition

Within my current project, I am utilizing vue.js 2 and have implemented an img component. Below is the code for this component: <template> <div class="banner"> <img class="banner-img" :src="bannerImg"/> </div> </template> ...

Exploring the nesting of client components in Next.jsIf you are

Exploring the realm of NextJS and React, I find myself delving into the realm of client components. One such client component I'm working with is called Form.jsx. It looks something like this: export default function FormHome() { ... a plethora of ...

Could someone please provide clarification on this specific JavaScript syntax? I am unsure about the usage of `const {

Although I am not very familiar with javascript, I have come across this syntax and I would greatly appreciate it if someone could help me understand it! Regarding Node.js const { check, validationResult } = require('express-validator/check') ...

Vue - a guide on customizing a prop in a parent component

I have implemented a wrapper component that encapsulates a Quasar q-select element in the following manner: <template lang="pug"> q-select( :options="organisations" option-value="id" v-bind="$attrs&quo ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...

Step-by-step guide to retrieving the value of a duplicate input field with identical IDs in Angular4

This is the form I am working on: <button (click)="M_add()">Add</button> <tbody id="_tbody"> </tbody> Whenever the add button is clicked, it triggers the creation of an input field. let tbody = document.getElementById("_tbody"); ...

Arranging items by their total sum of arrays in React.js

I'm working with data.js where I have stored my JSON information. Here's a snippet: [ { name: 'Adam Doe', city: 'New York', mark: [8,10,10,10] }, { name: 'Catlyn Stronk', ...

Ways to retrieve parameters in getStaticPaths function?

I'm currently working on a Next.js app with Contentful as the CMS. The file structure relevant to my question is: pages -[category] -[slug].js My goal is to access the category value when a user visits category/slug. Currently, I have the category ...

Top method for keeping track of most recent function outcome

Over time, I have become accustomed to utilizing the bind method to store the previous result of a function and keep track of it for future use. This allows me to easily concatenate or join the previous string with a new string without needing external var ...

Tips for personalizing the color scheme of Material UI Stepper Step?

I need help customizing the disabled Step color for Material UI Steppers. The default colors are Blue for enabled steps and Grey for disabled steps, but I want to change it to a different color as shown in this example: https://i.stack.imgur.com/HGGxp.png ...

Identification of input change on any input or select field within the current modal using JavaScript

My modal contains approximately 20 input and select fields that need to be filled out by the user. I want to implement a JavaScript function to quickly check if each field is empty when the user navigates away or makes changes. However, I don't want t ...

Utilize jQuery and JavaScript dynamically in an HTML document on iOS devices

Having some trouble with this code snippet and getting it to work as intended. - (void)viewDidLoad { [super viewDidLoad]; _webview.delegate = self; [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBun ...

The $http service factory in Angular is causing a duplication of calls

After creating an angular factory that utilizes the $http service, I encountered a problem where the HTTP request is being made twice when checking the network tab in the browser. Factory: app.factory('myService', function ($http, $q) { var de ...

The image is loaded correctly through the image picker, however, it is not displaying on the screen

When I click the button to pick an image from the gallery in this code, it is supposed to load the phone's gallery and display the selected image in the image component. Even though the image gets loaded properly (confirmed through test logs), it does ...

Display a particular div when a specific image is present within another div

I'm currently working on a task, but I'm having trouble with it. If I have an image called smiley.png within a div with the class "selected." <div class="selected" style=""><img width="25" height="24" src="images/smileys/smiley.png ...

Incorporation of a dynamic jQuery animation

I'm a beginner in jquery and I'm attempting to achieve the following: I want each menu to collapse separately when the mouse hovers over it. The issue is that both menus collapse simultaneously! I know it's probably something simple, but I ...