Why AngularJS ng-bind does not update the view

Why can't this small angular module update the view when the property changes ng-bind?

<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 expect the output to change to after 5 seconds Hello Jonif it stays on Hello Whirled. Why is this? Do I need to do something?

+4
source share
2 answers

use $intervalservice

Angular wrapper for window.setInterval here doc

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

do not forget to enter $intervalhow,

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

when using setIntervalit outside the angular scope, so you need to use it $intervalhere. $intervalruns against scope


OR use $scope.$apply()

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

$apply

+11

, $interval - . $scope. , angular . jQuery , . $Apply, angular - happend

+1

All Articles