Ali RAN
Ali RAN

Reputation: 563

Watching a property of global object in Angular JS

Suppose that you have an object in the global scope (I know it's bad. It's just for demo purposes), and you want to watch a property of that object in Angular JS.

var human = {
    name: 'Somebody'
};
var app = angular.module('app', []);
app.controller('watchController', function ($scope) {
    $scope.$watch('human.name', function () {
        alert('foo is changed');
    });
    $scope.doWatch = function () {
        human.name = new Date().toString();
    };
});

and this HTML:

<div ng-app='app'>
    <div ng-controller='watchController'>
        <input type='button' value='Invoke' ng-click='doWatch()' />
    </div>
</div>

How do you do that? This code doesn't work. See this fiddle.

Upvotes: 0

Views: 243

Answers (1)

AlwaysALearner
AlwaysALearner

Reputation: 43947

$watch accepts a function as the first parameter. A change in the return value triggers a call to the listener.:

$scope.$watch(function(){
    return human.name;
}, function () {
    console.log('foo is changed');
});

Fiddle

Upvotes: 4

Related Questions