What is the reason for the error message "ReferenceError: categories is not defined" appearing in my AngularJS code?

I don't understand why I am encountering this error and cannot access the data from the Json file, even though $scope.categories is already defined. Can someone help me with this issue?

Below is my controller code:

(function(){

    app.controller('productsCtrl', ['$scope','$cookies', '$http', function($scope,$cookies,$http){

        $http.get("controllers/data.json").then(function (response) {
            $scope.categories = response.data;
        }); 

        $scope.specials = [categories[0].laptops[1], categories[1].accessories[0]];

    }]);

})(); 

And here is a snippet of my Json file:

[
  {
    "laptops": [     
      {
        "name": "Asus Laptop",
        "price": 300
      },
      {
        "name": "HP Notebook",
        "price": 200
      }
    ]
  },
  {
    "accessories": [
      {
        "name": "WD Hard Drive",
        "price": 100
      },
      {
        "name": "WD Blue SSD",
        "price": 700
      }
    ]
  }
] 

Answer №1

Make sure to assign the response data into $scope.categories instead of just using categories. Also, after the HTTP call is completed, remember to add the data into $scope.specials as shown below:

(function(){

    app.controller('productsCtrl', ['$scope','$cookies', '$http', function($scope,$cookies,$http){

        $scope.specials = [];
        $http.get("controllers/data.json").then(function (response) {
            $scope.categories = response.data;
            $scope.specials.push($scope.categories[0].laptops[1]);
            $scope.specials.push($scope.categories[1]. accessories[0]);
        }); 

        

    }]);

})(); 

Answer №2

There are a couple of issues that need to be addressed here. Firstly, there is no variable named categories defined in the code, instead it appears to be a property of the $scope object. Therefore, you should access it using $scope.categories or by directly setting it with response.data.

Secondly, there seems to be a race condition problem. The code is attempting to access values from categories outside of the promise, which could potentially occur before the get request has returned any data. When using get().then(), the subsequent code is not synchronized to wait for the request to finish before executing. This can lead to conflicts where one operation runs before the other. Given that one operation involves an external endpoint while the other is local javascript code, the execution order is likely as follows:

  1. Send a get request to "controllers/data.json"
  2. Set $scope.specials - resulting in an undefined error.
  3. Set $scope.categories when the get request promise resolves.

To ensure that categories are accessed only after they have been defined, you should handle them inside the promise callback like this:

$http.get("controllers/data.json").then(function (response) {
    $scope.categories = response.data;
    $scope.specials = [$scope.categories[0].laptops[1], $scope.categories[1].accessories[0]];
}); 

Furthermore, hardcoding indexes as shown in the code is not recommended since changes in the data structure can lead to index out of bounds errors.

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

I am facing difficulties in showing the data in my Ionic view when attempting to connect to my php API

Attempting to utilize a PHP API for data display is posing a challenge. The PHP side appears to be functioning correctly, as the data is being displayed through echo. However, encountering an error when trying to fetch the data in the Ionic view using http ...

Rearrange the data pulled from a MySQL query

Data retrieved from MySQL database: Department Month Value Sales February 50 Sales March 35 Sales April 65 Sales May 120 Dispatch February 85 Dispatch March 23 Dispa ...

The toggle button for columns is not triggering the callback action

When working with the following JSFiddle, I noticed that the action function does not seem to fire whenever a button to select a column in the column visibility tool is selected. Check out the code snippet below for reference: $(document).ready(function( ...

Guide on transferring a file to Node.js using FormData and receiving a confirmation response from Node

Hello, I'm currently working on a basic form where I'm attempting to send a file to my Nodejs server using the FormData object. However, I'm facing an issue as my Node server does not seem to receive the file. Additionally, I would like to k ...

Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key. Even after querying and attempting to return the variable queryre ...

There seems to be a discrepancy with the IP to hex conversion equation in my JavaScript code. The result I'm getting doesn't align with what other

How to check if an item is a valid IP address (e.g. 254.253.242.222)? `var h0 = Math.pow(256,0);` `var h1 = Math.pow(256,1);` `var h2 = Math.pow(256,2);` var h3 = Math.pow(256,3); var splitup = item.split('.'); var iHex = ...

Tips for successfully transferring a concealed value within a form

<p>{{item.name}}</p> // This part is functioning properly and displays correctly <form #f="ngForm" (ngSubmit)="onSubmit(f.value)" novalidate> <div *ngIf="editMode"> <input name="name" type="hidden" ngModel val ...

JavaScript JSON function failing to show

I apologize for my limited knowledge on this matter... We are currently facing an issue with our website's pricing page. The dynamic calculator, which should display the price based on user input of size width and quantity, is not functioning as expe ...

finding the source file or code where a particular html element is being generated

In the HTML file I have, there are multiple JavaScript files added. Whenever I run the HTML file, a title tag is automatically created in my HTML file. I do not want this title tag to appear in my HTML file. How can I prevent this from happening? Or how c ...

Unable to backtrack once a response has been sent

My Express application keeps crashing after sending a response to the client. It appears that the code continues to run even after the response has been returned. Can you please review the code snippet provided below? const EditUser = async (req, res) => ...

Transitioning from using sendfile() to sendFile() function within the Express framework

Here is the code snippet I am using: router.get('/image',(req,res,next)=>{ const fileName = "path_to.jpg" res.sendfile(fileName,(err)=>{ if (err) { next(err); } else { console.log('Sent:', fileName); } ...

The scrollbar will be visible only when the mouse hovers over the table

I have been experimenting with customizing the scrollbar appearance of an ant design table. Currently, the scrollbar always displays as shown in this demo: https://i.stack.imgur.com/vlEPB.png However, I am trying to achieve a scroll behavior where the sc ...

What is the process for including an additional bar in a Google bar chart?

Trying to enhance my google bar chart by adding an extra horizontal bar, but facing challenges in integrating it smoothly with the existing chart. JS Code <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> ...

JavaScript code does not run when a page is being included

On my AngularJS-based page, I have included some additional HTML pages like this: <div data-ng-include src="includehtml"></div> Here is the JavaScript code: $scope.selectImage = function(id) {$scope.includehtml = id;} (I pass the HTML file ...

There seems to be an issue with Jquery not triggering the Webservice method in the Firefox browser, despite it working successfully in Chrome

Currently, I have an issue where a webservice method called via ajax in jQuery is functioning correctly in Chrome and IE browsers but not in Firefox. Here is the jQuery code: $("#btnUpdate").click(function () { var objEmp = { employeeID: $("#Em ...

Navigating within fixed-positioned divs

I'm attempting to create something similar to the layout seen on: The desired effect is to have fixed content on the right side, with only the left side scrolling up to a certain point before the entire page scrolls normally. However, in my implement ...

Unlocking Windows credentials through an AngularJS application and seamlessly incorporating them into the service layer

I've been pondering a solution for the challenge outlined below. At my workplace, we utilize Visual Studio Team Services (formerly known as Visual Studio Online), which is seamlessly integrated with our Active Directory. This allows me to access Team ...

Using Froala events in Angular 2: A guide

Currently, I am incorporating Froala into my Angular 2 project. I have managed to upload an image successfully but am encountering issues triggering the image.uploaded event. The Froala document provides an example of how the event should be implemented: ...

Utilize Typescript/Javascript to utilize the Gmail API for sending emails via email

I am trying to send emails from my application using my Gmail account with Ionic. I have followed tutorials from SitePoint and Google Developers. Here is how I'm initializing the client: client_id: gapiKeys.client_id, discoveryDocs: ["https://www.goo ...

JavaScript - Utilizing an image file in relation to a URL pathway

Is there a way to reference an image URL using a relative path in a JavaScript file similar to CSS files? To test this, I created two divs and displayed a gif in the background using CSS in one and using JavaScript in the other: -My file directory struct ...