Unusual behavior observed in AngularJs local variables

This code snippet is from the controller:

cat1=[];

$.getJSON('categories/1/', function(data) {
    cat1 = data; //this returns a JSON object
});
//cat2..4 are also JSONs
$scope.pictures=[cat1,cat2,cat3,cat4,cat5];

The issue here seems to be that cat1=[] and cat1=data might not be treated as the same variable, leading to pictures[cat1] always returning an empty array.

Could there be something incorrect in my code logic?

Answer №1

The reason why logging the result of $.getJSON may not work is because it is an asynchronous request that is still processing. Additionally, it is recommended to use Angular's built-in $http service instead of jQuery when working with Angular. This ensures that a $digest cycle is triggered and everything stays in sync:

$http.get("categories/1/").success(function(data) {
    cat1 = data; // returns JSON data
    $scope.pictures=[cat1,cat2,cat3,cat4,cat5];
});

Don't forget to inject $http as a dependency in your controller:

app.controller("myCtrl", ["$scope", "$http", function($scope, $http) {

}]);

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 the process for extracting values from a Proxy object and assigning them to a local variable?

Can anyone help guide me on how to retrieve a list of devices (video and input/output audio) using navigator.mediaDevices.enumerateDevices()? I created a function that returns the result, but when I try to display it with console.log(result), I only see a ...

troubles with variables in AngularJS Formly templates

Having trouble displaying model or other variables in my template? Check out this link for reference: http://jsbin.com/wofulinufo/edit?html,js,output. Question: What is the solution for displaying variables from controller? Even when I try using {{model} ...

Emptying the trumbowyg editor within an Angular environment

I am currently experiencing issues with the trumbowyg editor in a project I'm working on. I am able to update the editor by changing its model but cannot seem to clear its content using $scope.editorModel = '';. For a more detailed explanati ...

Design an interactive div element that allows users to modify its content, by placing a span

Here is an example of the desired effect: ICON LINE - 1 This is some sample text inside a div element and the next line should begin here ICON LINE - 2 This is some sample text inside a div element a ...

Executing multiple AJAX requests with promises in Angular based on an array of values

I have been working on implementing multiple ajax calls in sequence using Angular. Interestingly, everything seems to be working fine when I use $.ajax, but when I switch to using $http for server requests in Angular, things start to go awry. Both methods ...

Transmit information from Ajax to CodeIgniter's controller

Right now, I am facing an issue with sending data from my JavaScript to a function in the controller using AJAX. Despite my best efforts, AJAX is not sending the data. Below, you can find the code that I have been working on: The JavaScript Function var ...

Tips for submitting a form using javascript while preventing the default action

Looking for a way to submit a form in Javascript and prevent the default action? Let's explore how you can achieve this. Initially, my HTML form with the ID "contact_form" had an input element like so: <input id="contact_send_msg" type="submit" val ...

Changing the height of one Div based on another Div's height

I currently have a display of four divs positioned side by side. I am seeking a solution to ensure that the height of each div remains consistent, and should adjust accordingly if one of them increases in size due to added text content. For reference, ple ...

Creating multiple AJAX contact forms can be achieved by modifying the code to accommodate multiple forms on a single page. Here's

My one-page website features 15 identical contact forms all with the same ID, created using basic PHP. Unfortunately, I am facing an issue where AJAX is only working for the first form. When submitting any other form, it simply opens a white page with a "T ...

When trying to access the key value of a dynamically generated object, it returns as undefined

I am facing a challenge with my student object structure... { Freshmen: [{id: 3}, {id: 5}], Sophomores: [{id: 2}, {id: 6}], Juniors: [{id: 1}, {id: 8}], Seniors: [{id: 9}, {id: 4}, {id: 7}] } My goal is to retrieve full student objects from the d ...

issue with data binding in ons-dialog

Utilizing an ons-dialog to display a popup prompting the user to sign up for a newsletter. I have set a 3-second timeout to prevent users from immediately closing the prompt without reading it or waiting. I aim to initially show the dialog with the ' ...

Regex for US zip code with an optional format

Searching for a regular expression to validate US zip codes. I have come across multiple examples, but none of them cater to the scenario where the zip code is optional. The input field I am working on does not require a zip code, so it should accept a 5 ...

The fixed positioned div with jQuery disappears when scrolling in Firefox but functions properly in Chrome, IE, and Safari

Click here to see a div located at the bottom of the right sidebar that is supposed to behave as follows: As you scroll down the page, the div should change its class and become fixed at the top of the screen until you reach the bottom of the parent el ...

Managing JavaScript promise rejections

What is the best approach to managing an error, such as the one labeled "new error" in the code snippet below, that occurs outside of a promise? function testError() { throw new Error("new error") // How can this error be properly handled? var p ...

Using setState in an external function: A step-by-step guide

import Request from 'superagent'; const fetchApi = () => { let apiUrl = '/* URL */'; return Request.get(apiUrl).then((response) => { this.setState({ data: response.body }); }); } export d ...

Adjusting data points on a radar chart.js through user interaction

I have a radar map generated using chart.js, along with some input fields where users can enter values that I want to reflect in the graph. I am exploring ways to update the chart dynamically as the user types in the values. One option is to have the char ...

Error: Jest encounters an unexpected token 'export' when using Material UI

While working on my React project and trying to import { Button } from @material-ui/core using Jest, I encountered a strange issue. The error message suggested adding @material-ui to the transformIgnorePatterns, but that didn't resolve the problem. T ...

The jQuery countdown plugin is yielding some unexpected outcomes

Feeling a bit rushed for time, so I thought I'd ask here. The date is currently 2012-10-06 and I'm attempting to implement a jQuery plugin called "jquery.countdown.js". It seems pretty straightforward. Can anyone point out what I might be doing i ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

Is there a way to retrieve a comprehensive list of all the potential routes in my nuxt.js project?

Is there a way to retrieve a list of all the potential routes in my nuxt.js project? (this would include all URLs) ...