Let me start by saying that what I am trying to do is probably not considered good practice. However, I need to do something like this in order to migrate a large web app to AngularJs in small incremental steps.
I tried doing
$scope.$watch(function () { return myVar; }, function (n, old) {
alert(n + ' ' + old);
});
Where myVar is a global variable (defined on window)
And then changing myVar from the console. But it only fires when first setting up the watcher.
It works if I update myVar from within the controller (see http://jsfiddle.net/rasmusvhansen/vsDXz/3/, but not if it is updated from some legacy javascript
Is there any way to achieve this?
Update I like Anders' answer if the legacy code is completely off limits. However, at the moment I am looking at this approach which seems to work and does not include a timer firing every second:
// In legacy code when changing stuff
$('.angular-component').each(function () {
$(this).scope().$broadcast('changed');
});
// In angular
$scope.$on('changed', function () {
$scope.reactToChange();
});
I am awarding points to Anders even though I will go with another solution, since his solution correctly solves the problem stated.