Monojit Sarkar Monojit Sarkar -4 years ago 37
AngularJS Question

AngularJS: init data from js timer not working

i am new in angular. i was reading the functionality of

$scope.$apply();

i got a sample where controller's data member value is assign from timer but change was not reflected in UI but when i use
$scope.$apply();
then change reflect to UI.........why?

i define timer inside my controller so if i assign any data to controller's data member then change should come. tell me what was the problem with timer that if we assign any data to controller's data member change is not coming to UI.

see my code



<div ng-app="myApp" ng-controller="FirstCtrl">
{{message}}
<br>

<button ng-click="myFunc()">OK</button>
</div>

var myApp = angular.module('myApp', []);

myApp.controller('FirstCtrl', function( $scope ){
$scope.message = "Waiting 2000ms for update";

setTimeout(function () {
$scope.message = "Timeout called!";
// AngularJS unaware of update to $scope
alert("alert called");
$scope.$apply();
}, 2000);

$scope.myFunc = function() {
$scope.message = "Timeout called!";
};

});

Answer Source

setTimeout is javascript function. it causes digest cycle to stop running. That's why you need to use $scope.$apply() to manually start the digest cycle.

alternatively, you can use $timeout service instead of setTimeout. $timeout is angular in build service so it will not cause any problems to the digest cycle

$timeout(function () {
        $scope.message = "Timeout called!";
        // AngularJS unaware of update to $scope
        alert("alert called");
        $scope.$apply();
    }, 2000);

Make sure to inject the $timeout to your controller

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download