Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why AngularJS ng-bind does not update the view

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?

like image 344
Sam R. Avatar asked Dec 15 '22 16:12

Sam R.


1 Answers

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

like image 178
Kalhan.Toress Avatar answered Dec 30 '22 07:12

Kalhan.Toress