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

retrieve JSON information using JSONP

Currently, I am working with a URL that returns data in JSON format. Here is the URL: http://10.0.1.11/render?target=threshold(400,test)&from=-1mins&format=json&jsonp=? When I enter this URL into a browser, it displays the following JSON re ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

Executing function inside an Angular factory

I am currently working with an Angular factory that contains various functions. My goal is to use myService to retrieve data, and upon successful retrieval, call another function within the factory: myApp.factory('myFactory', function($http) { ...

What is the preferred method for logging out: using window.location.replace('/') or setting window.location.href to window.location.origin?

When it comes to a logout button, which is the better option: window.location.replace('/') or window.location.href=window.location.origin? Can you explain the difference between these two methods? It's my understanding that both of them remo ...

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

Determining when all promises have either been rejected or resolved using vanilla JavaScript promises

In an effort to transition to loading all resources in my web application asynchronously using basic JS promises, I have implemented a ScriptLoader function. Below is the code snippet for the ScriptLoader used to load .js files: function ScriptLoader() { ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

Updating a single document in Node JS using Express is a simple and straightforward process

I'm having trouble understanding why my documents aren't updating. When I retrieve any record and load it into the form using http://localhost:3000/update2?buyerID=2299, the field doesn't update when I make changes and click submit. It rema ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

Refreshing JSON data in AngularJS: How to update only the changed content in an ivh-tree using REST API

After making a REST API call to fetch JSON data in tree format, I save it in a scope variable called $scope.treeData[]. This data is then displayed in an ivh-tree. To keep the data up to date, I use an interval to update it every 60 seconds. The issue ar ...

Adjust the time increment dynamically within the dropdown menu

I have a challenge to make a dynamic dropdown field that adjusts based on the value of a previous input field. There is a dropdown for selecting length, with options like 30 min., 60 min., and 90 min.. Additionally, there are input fields for startTime and ...

What is the best way to utilize the ajax factory method in order to establish a $scoped variable?

One issue I frequently encounter in my controllers is a repetitive piece of code: // Get first product from list Product.get_details( id ) .success(function ( data ) { // Setup product details $scope.active_product = data; }); To avoid this ...

Choose all elements by their class except for a particular container defined by the parent element's ID

Can you provide an example of translating the function below into utilizing the .not method (or not selector)? $(".CLASS").filter(function(i, e){ return (e.parentNode.id != "ID"); } ...

What is the best way to iterate through data with ajax and mysql?

I have a school project where I need to create an MP3 album playlist using a premade PHP API with JavaScript or jQuery (without using PHP). I can input the data via an AJAX call. The goal is to add multiple songs along with their URLs into a column named s ...

Enhance Bootstrap modals by automatically adjusting the background shadow mask when resizing or changing the content within the modal window

Incorporated within my bootstrap modal window is a form alongside a link that triggers the jQuery functionality of .slideToggle(). By interacting with this link, a concealed div expands. Consequently, the size of the modal popover becomes fluid. Upon click ...

What is the process for exporting an NPM module for use without specifying the package name?

I am looking for a way to export an NPM module so that it can be used without specifying the package name. Traditionally, modules are exported like this: function hello(){ console.log("hello"); } module.exports.hello = hello; And then imported and ...

prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involve ...

Error encountered: Cordova plugins return undefined values when testing on an actual device

I am currently utilizing Phonegap in conjunction with ngCordova and AngularJS. The aim is to leverage the capabilities of the plugin (PhoneGap-Image-Resizer) to facilitate media saving on the device. However, I encountered an issue where the plugin throws ...

Tips for utilizing import alongside require in Javascript/Typescript

In my file named index.ts, I have the following code snippet: const start = () => {...} Now, in another file called app.ts, the code is as follows: const dotenv = require('dotenv'); dotenv.config(); const express = require('express' ...

Retrieve and access an array of objects from MongoDB

Assuming I have some data stored in MongoDB as follows - [ { _id: new ObjectId("63608e3c3b74ed27b5bdf6fa"), latitude: 24.3065, hotels: [ { name: "Saunders Oconnor", lat ...