Reputation: 77
Here's my app.js
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyController', ['$scope', function($scope){
$scope.watchMe = 'hey';
$scope.init = function() {
setTimeout(function() {
$scope.watchMe = 'changed!';
}, 3000)
};
$scope.$watch('watchMe', function() {
console.log($scope.watchMe)
});
}]);
I thought, after 3 seconds, I'd see:
'changed!'
in my console.
Instead, I just see:
'hey'
I call my init() function in index.html, as such:
<div ng-controller="MyController" ng-init="init()">
Why am I seeing this output?
Upvotes: 0
Views: 84
Reputation: 2994
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyController', ['$scope', '$timeout', function($scope, $timeout){
$scope.watchMe = 'hey';
$scope.init = function() {
$timeout(function() {
$scope.watchMe = 'changed!';
}, 500);
};
$scope.$watch('watchMe', function(newVal, oldVal) {
console.log(newVal);
});
}]);
you are using setTimeout method. Angular is not watching that event. use $timeout service of angular then you can see the expected result.
Read about angular digest loop and dirty checking for more detail.
Upvotes: 1