0

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.

2
  • "I know it's bad" - so don't do it. Map your model objects to view models and watch those instead. Also - to see how watchers work see teropa.info/blog/2013/11/03/… Commented Nov 26, 2013 at 13:01
  • @BenjaminGruenbaum - I guess plain curiosity is good enough reason ;) Commented Nov 26, 2013 at 13:02

1 Answer 1

4

$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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.