Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating $scope using .getJSON()

Tags:

angularjs

I started playing with Angular.js recently, and got a demo project working pretty well. However, when I attempted to load the data from a backend web service versus just a hard coded array I started getting hung up. Specifically the page doesnt seem to properly data bind after i set the $scope using $.getJSON().done(...). Instead of just assigning a value to $scope after .getJSON is done, should I be doing it somewhere else/differently? I searched high and low and really couldnt find any good examples of angular thats pulling intial data from a backend.

Thanks in advance for any help with this!

like image 797
jkat98 Avatar asked Aug 24 '12 17:08

jkat98


1 Answers

Since you are trying to update the $scope outside of Angular you will have to make your model changes using the $apply method on the scope.

Maybe something like:

    $.getJSON('ajax/test.json', function(data) {
        $scope.$apply(function(){
            $scope.modelData = data;
        });
    });

The preferred way to access a backend with AngularJS would be to use the $http or $resource service in place of jQuery. You won't have to use $scope.$apply you can just update your $scope.modelData directly.

This post has a good fiddle of updating a model outside of Angular code.

like image 121
Gloopy Avatar answered Sep 27 '22 18:09

Gloopy