angular $watch learning (listening array)

The article refers to http://blog.csdn.net/u010451286/article/details/50635839

Question:
When you use the above two methods to monitor the array, you will find that even if the content of the array changes, this anonymous function is not triggered?

Analysis:
The watch function actually has three variables. The first parameter is the object to be monitored, and the second parameter is the function that needs to be called when the monitored object changes. In fact, watch has a third parameter, which is by default case is false. 
When the third parameter is false, in fact, the watch function monitors the address of the array, and the change of the content of the array will not affect the change of the array address, so the watch function fails

The solution is to add a third parameter as true at the back.

example:

$scope.items=[
{a:1},
{a:2}
{a:3}];
$scope.$watch('items',function(){...},true);

 


 $watch listens to multiple variables

example:

 

//When count or page changes, this anonymous function will be executed
$scope.count=1;
$scope.page=1;
$scope.$watch('count + page',function(){
...
});

 

The return result of the $watch function

 When writing code, sometimes you need to monitor whether the result returned by a function changes, so check the $watch monitoring function.

Method 1: The monitoring object is a string of "function name ()", remember to add "()"!

 

//Number of unfinished tasks
$scope.unDoneCount = function() {
    var count = 0;
    angular.forEach($scope.todoList, function(todo) {
        count += todo.done ? 0 : 1;
    });
    return count;
};
//Single selection affects all selections
$scope.$watch('unDoneCount()', function(nv) {
    $scope.isDoneAll = nv ? false : true;
});

 

Method 2: Set it as an anonymous function in the monitoring object, and return the return value of the function to be monitored (confused...)

 

$scope.$watch(function(){
    return $scope.unDoneCount();//Don't forget (), it needs to be executed~
}, function(nv) {
    $scope.isDoneAll = nv ? false : true;
});

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326765738&siteId=291194637