Sam
Sam

Reputation: 15761

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);
    }

}]);

Upvotes: 0

Views: 90

Answers (1)

PixnBits
PixnBits

Reputation: 1162

To expand on the comment from @still_learning above, only Functions 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 Arrays
  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/

Upvotes: 2

Related Questions