Angular $watch | returning the item from function

后端 未结 4 1431
借酒劲吻你
借酒劲吻你 2021-01-13 11:03

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

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


        
4条回答
  •  孤街浪徒
    2021-01-13 11:16

    Since the how-to-do answer is already given, I'll try to explain you what goes on actually and why it didn't work the way you tried at first time.

    First of all this code sure works,

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

    But this is NOT the perfect way. To be more precise $watch injects the scope in the function, like this,

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

    Previously it works because $scope and injectScope are one and the same thing.

    Now as this article explains,

    Since $scope is passed into the watch function, it means that we can watch any function that expects the scope as an argument and returns a value in response. A great example of this is $interpolate function.

    So in your case, we can also make use of $interpolate as following:

    $scope.$watch($interpolate("{{someData}}"), function(value) {
        ...
    });
    

    Now this is where we come to the short-hand method of using just a watch expression. $watch can also accept an expression, which actually is interpolated.

    Thus by providing $scope.$watch("someData", ... ),

    someData will be:

    1. interpolated as {{someData}}
    2. using the scope injected by $watch function

    This is a nice, clean, readable, short-hand way of writing the expression instead of the actual function. But finally after all such compilations, it is ultimately the function which returns a value to watch.

提交回复
热议问题