简体   繁体   中英

AngularJS $watch not working for filtered ng-repeat

I'm attempting to use $watch on a filtered list of data, but it doesn't seem to work. Here is a snippet of my code.

HTML:

<div ng-repeat="dlr in dealers | filter : filterDealers ">
    {{dlr.name}}
</div>

Controller

$scope.$watch('dealers', function () {
    console.log('dealers was changed');
});

$scope.filterDealers = function (dlr) {
    if (dlr.name = 'test') {
        return true;
    } else {
        return false;
    }
}

The console.log is printed when the page loads, but if I filter the list, it doesn't get printed.

If you only need to know when the data is filtered, simply filter the dealers in your controller.

 <div ng-repeat="dlr in filteredDealers ng-init=filterDealers>"> 
     {{dlr.name}}
 </div>

And in your controller do:

$scope.filterDealer = function() {
    $scope.filteredDealers = [];
    for (var i=0; i<dealers.length; i++) {
        var dlr = dealers[i];
        if (dlr.name = 'test') {
            $scope.filteredDealers.push(dlr);
        }
    }
    // you know your filtering is done
    console.log('dealers was changed');
}

I do not think you will want to set a $watch on a 2 way bound $scope variable. IF you want a function to run when your ng-repeat is done running, you can make a small directive and check $last

Something like this :

.directive('isLastItem', function () {
 return {
    restrict: 'A',
    link: function (scope, element, attr) {
        if (scope.$last === true) {
            //run your logic here
        }
    }
 }

then the html

<div ng-repeat="dlr in dealers | filter : filterDealers " is-last-item>

Now - I don't know where you want this logic to happen so you might want to $emit from your directive to your controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM