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:
if reassign
$scope.students
new array, $watch may still looking @ previous array (reference). try usingangular.copy()
in "after" code:
angular.copy(data, $scope.students);
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
Post a Comment