I want to trigger things ONLY when a variable changes its value. The aim is to use this variable as a flag to indicate that a database is ready to be used, and then to use the $watch to detect when this happens and continue with something else.
The simplified version of this would be the following:
<div ng-app="watchApp" ng-controller="watchCtrl">
{{status}}
</div>
and
angular.module('watchApp', []).controller('watchCtrl',
['$scope', 'myVariables',
function($scope, myVariables) {
$scope.status = myVariables.myVar;
$scope.$watch(
function() {return myVariables.myVar;},
function(newVal, oldVal) {
$scope.status = 'changed';
}
);
setTimeout(function(){myVariables.myVar = 1;alert('ei');},1000);
}]);
angular.module('watchApp').factory('myVariables',
['$window', '$q',
function($window, $q) {
return {
myVar: 0,
}
}]);
http://jsfiddle.net/SQuVy/218/
So, the timeout should change the variable after 1 second, and then the watch should trigger the cascade and change the displayed message.
But it does not work. Why? Perhaps because within the Timeout I do not have access to the variable? Here the Timeout is to exemplify the problem, but it does not exist in my code. How could I do this?
Cheers, Gerard