javascript - $scope.$watch isn't firing after load in angular.js -


i'm using angular.js , trying use $watch fire function when variable changes. fires when data loaded, not after. i'm not sure going on here?

code pasted below:

function gradechart($scope, $http) {    $http.get('studentdata.json').success(function(data) {        $scope.students = data;    });      $scope.$watch('students',function(change){        console.log('this fires on load not after');     }); } 

it not clear code runs "after" , updates $scope.students.

however, here 2 common problems related updating $scope arrays:

  1. if reassign $scope.students new array, $watch may still looking @ previous array (reference). try using angular.copy() in "after" code:
    angular.copy(data, $scope.students);

  2. if changing 1 of elements of array, you'll need use either $watchcollection (if available in version of angular using) or check object equality instead of reference (note 3rd parameter):
    $scope.$watch('students',function(change){...}, true);


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -