I am expecting $watch
to fire x
times if you change the variable it is watching x
times. In a little example I put together, I am changing the value of variable $scope.foo
3 times, but the associated $watch
only runs once...
<html>
<head>
<title></title>
<script src="https://code.angularjs.org/1.3.8/angular.js"></script>
</head>
<body ng-app='myApp'>
<div ng-controller='MyCtrl'></div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.$watch('foo', function(oldVal, newVal) {
console.log(oldVal, newVal);
});
$scope.foo = "foo";
$scope.foo = "bar";
$scope.foo = "baz";
});
</script>
</body>
</html>
Would anyone be able to explain what the reason for this is, or a different approach I can take to receive the desired outcome?
I am expecting the following console output:
undefined foo
foo bar
bar baz
but get...
baz baz
edit: another example
myApp.controller('MyCtrl', function($scope, $timeout) {
$scope.$watch('foo', function() {
$scope.bar = 'bar';
});
$scope.foo = "foo";
// now the value of $scope.foo has changed, I was expecting the $watch to have run at this point.
// Apparently is has not because $scope.bar is still undefined. Accessing $scope.bar in a $timeout works, but is there a better way?
console.log($scope.bar)
});