Understanding $watch in AngularJS?

12,068

That's pretty simple:

function myFunction(foo) {
    // do something with `foo`
}

$scope.$watch('foo', function(newValue, oldValue) { 
    myFunction(newValue);
});

More details are found in the AngularJS documentation about $watch.

Share:
12,068
Foo Stack
Author by

Foo Stack

Updated on June 09, 2022

Comments

  • Foo Stack
    Foo Stack almost 2 years

    I am a little confused with the $watch syntax in AngularJS.

    Given a variable $scope.foo, with initial value of [1,2,3], and update causes it to now equal [1,2]. I want a function to be run whenever $scope.foo is updated, with $scope.foo as arg.

    How do I do this in AngularJS?

  • TidharPeer
    TidharPeer almost 11 years
    You can add the $ sign before the 'scope'
  • Moritz Petersen
    Moritz Petersen almost 11 years
    @TidharPeer You're right, done that.
  • Foo Stack
    Foo Stack almost 11 years
    Thanks, but I can't seem to get it to work with $http, here's what I've tried.