简体   繁体   中英

AngularJS $scope.$watch on an object's properties

I am trying to watch a simple object on $scope, but I am confused as to why the following always outputs state:{value} for both the country and state select elements.

angular.module('app').controller('FiltersCtrl', ['$scope', 'filterRepo', function ($scope, filterRepo) {

    $scope.data = {
        lookups: {
            countries: [
                { id: 1, name: 'USA' },
                { id: 2, name: 'Canada' },
                { id: 3, name: 'Mexico' }
            ],
            states: [
                { id: 1, name: 'Oregon' },
                { id: 2, name: 'Texas' },
                { id: 3, name: 'Iowa' }
            ]
        }
    };

    $scope.query = {
        filter: {
            country: 1,
            state: 1
        }
    };

    for (var item in $scope.query.filter) {
        $scope.$watch('query.filter.' + item, function (newValue, oldValue) {
            if (newValue !== oldValue) {
                console.log(item + ' : ' + newValue);
            }
        }, false);
    }

}]);

To expand on the comment from @still_learning above, only Function s have scope, meaning that the callbacks to your $watch statements are using the item variable you declared in the"parent" function. However, by the time these $watch callbacks are invoked/called, the for loop has already updated their values. There's an item about this in EffectiveJs ( Item 13 ).

A great answer is to use the power of function closures via .forEach . Two downsides:

  1. Only for Array s
  2. Only in the latest browsers

Angular provides a very convenient method to address both of these concerns in angular.forEach .

All this might sound rough :) but have a look at it in action in fiddle: http://jsfiddle.net/E62VE/3/

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