4

Why this little angular module can't update the view when the ng-bind property is changed?

<body ng-app="bindExample">

<script>
  angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      var vm = this;
      vm.name = 'Whirled';
      window.setInterval(function(){ vm.name = 'Jon';}, 5000);
    }]);
</script>

<div ng-controller="ExampleController as vm">
    Hello <span ng-bind="vm.name"></span>!
</div>
</body>

I'm expecting that after 5 seconds the output changes Hello Jon by it stays at Hello Whirled. Why is this? Do I need to do anything else?

Sam R.
  • 16,027
  • 12
  • 69
  • 122

2 Answers2

10

use $interval service its

Angular's wrapper for window.setInterval here is the DOC

$interval(function(){
     vm.name = 'Jon';
}, 1000);

don't forget to inject $interval as,

.controller('ExampleController', ['$scope', $interval, function($scope, $interval) { ....

when using setInterval its out of the angular scope so u need to use $interval here. $interval is execute against scope,


OR use $scope.$apply()

window.setInterval(function(){
    vm.name = 'Jon';
    $scope.$apply();
}, 5000);

$apply enables to integrate changes with the digest cycle

this answer would be helpful

Community
  • 1
  • 1
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
  • Thank you. If I call an AJAX to read the value and then apply it to the model in my resource `success` function, do I need to use `$apply` as well? – Sam R. Feb 10 '15 at 09:07
  • 1
    If you use angular's $http service for retrieving data from server, so no need to call $scope.apply(); – Rakhat Feb 10 '15 at 09:15
  • 1
    NO if you use angular `$http` service as #neilhem mentioned in the last comment, but if you use like jquery ajax you need to use `$apply()` there to tell the angular to there is something out side the scope and need to bind to the scope. – Kalhan.Toress Feb 10 '15 at 09:37
1

Yes, to use $interval is a solution. Usually you would change the model on a method attribute of $scope. So angular will take the responsibility of updating the view. If you use a jQuery callback inside a directive you would have to use scope.$apply so that angular knows something happend

Raulucco
  • 3,406
  • 1
  • 21
  • 27