Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $watch | returning the item from function

I'm interested to find out why i always have to do this

$scope.$watch( function() {
   return $scope.someData;
}, function( value ) {
   console.log( value );
});

for angular to actually watch the data, why do I have to do this, this is one of the things that really bug me because it looks pointless.

If I do something like this

$scope.$watch($scope.someData, function( value ) {
   console.log( value );
});

Which is nicer, it never works?

I also use this a lot with factories

say that $data is a factory I have to do

$scope.$watch( function() {
   return $data.someData;
}, function( value ) {
   console.log( value );
});
like image 888
iConnor Avatar asked Aug 13 '13 16:08

iConnor


2 Answers

I guess it's worth mentioning that passing a function to $watch is useful when you want to monitor a condition:

$scope.$watch(function() { 
    return $scope.data.length > 0; 
}, function() {
    // Do something every time $scope.data.length > 0 changes
});

or

$scope.$watch(function() { 
    return $scope.prop1 && $scope.prop2;
}, function() {
    // Do something every time $scope.prop1 && $scope.prop2 changes
});
like image 160
Michael Benford Avatar answered Sep 30 '22 20:09

Michael Benford


This works:

$scope.$watch("someData", function( value ) {
   console.log( value );
});
like image 34
AlwaysALearner Avatar answered Sep 30 '22 21:09

AlwaysALearner