I have a function getData which just increments value of var counter.
Whenever an increment takes place, I want angular to automatically update that inside a div
I've tried ng-bind but it only works if I click on a form element.
enquire.controller('DisplayEnquiries', function($scope){
$scope.getData = function(){
console.log('Run ' + $scope.counter);
$scope.counter;
if($scope.counter == undefined || $scope.counter == null){
$scope.counter = 1
$scope.counter++;
}
else{
$scope.counter++;
}
console.log('Execute ' + $scope.counter);
$scope.count = $scope.counter;
}
setInterval($scope.getData, 1000);
});
HTML
<div class="col-sm-5" ng-controller="DisplayEnquiries">
<h4>Unread User Queries</h4>
<p>
Count : <span ng-bind="count"></span>
</p>
</div>
Angular do have digest system which helps to provided updated binding over the view. But When you updated angular bindings from outer world of angular like any (async) event
, angular doesn't understand the change, resultant digest cycle won't get fire to updated binding. So in your case you are running setInterval
(async event) which is updating binding.
In such scenario you need to manually kick of digest cycle ($scope.$apply()
/$scope.$digest()
) to look for change and update binding accordingly over the view. But still I'd prefer you to use $interval
service which is provided out of the box which does same work as setInterval
& that does take care of digest cycle to keep binding in sync.
You should use $interval
instead of setInterval
$interval($scope.getData, 1000);