AngularJS does not update model changes

I am trying to figure out how Angular works, and I am having problems updating my view when the model changes.

HTML

<div ng-app="test"> <p ng-controller="TestCtrl"> {{testValue}} </p> </div> 

Js

 var app = angular.module('test', []); app.controller('TestCtrl', function ($scope) { $scope.testValue = 0; setInterval(function() { console.log($scope.testValue++); }, 500); }); 

http://jsfiddle.net/N2G7z/

any ideas?

+62
javascript angularjs
Nov 19 '13 at 11:18
source share
4 answers

As mentioned above in Ajay beniwal, you need to use Apply to start digestion.

 var app = angular.module('test', []); app.controller('TestCtrl', function ($scope) { $scope.testValue = 0; setInterval(function() { console.log($scope.testValue++); $scope.$apply() }, 500); }); 
+103
Nov 19 '13 at 11:56
source share

Just use $ interval

Here is your code modified. http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview

 var app = angular.module('test', []); app.controller('TestCtrl', function ($scope, $interval) { $scope.testValue = 0; $interval(function() { $scope.testValue++; }, 500); }); 
+32
Nov 19 '13 at 11:41
source share

setTimout runs outside of angular. To do this, you need to use the $timeout service:

 var app = angular.module('test', []); app.controller('TestCtrl', function ($scope, $timeout) { $scope.testValue = 0; $timeout(function() { console.log($scope.testValue++); }, 500); }); 

The reason is because two-way binding in angular uses dirty checking. This is a good article to read a dirty angular check. $scope.$apply() starts the $digest loop. This will apply the binding. $timeout handles $apply for you, so it is recommended that you use this function when using timeouts.

Essentially, the binding occurs during the $digest cycle (if the value is considered different).

+28
Nov 19 '13 at 11:19
source share

Do not use $scope.$apply() angular already uses it and this may lead to this error

$ rootScope: inprog Action already completed

if you use twice use $timeout or interval

+6
Jan 18 '17 at 10:40
source share



All Articles