Search code examples
javascriptangularjsfor-loopangularjs-watch

AngularJS - Trouble with $watch


I am trying to remove the "Red" and "Blue" drop down list options on a product SKU, if the user is a member of the "High" group on my store site. The code that I came up with is below, but only partially works; the only thing that works is the window alert. Now, if I remove the logic about looking up the user's group, then it does work, however the user has to set the value of the color drop down to begin with.

function SpecController($scope) {
    angular.forEach($scope.user.Groups, function (g) {
        if (g.Name == "High") {
            alert('You are in the correct group!');
            $scope.$watch('user.Groups.Name', function (val) {
                if (!val) return;
                if (val == "High") {
                    $scope.Variant.Specs.Color.Options = $scope.Variant.Specs.Color.Options.filter(function (item) {
                        return item.Value !== 'Red' && item.Value !== 'Blue';
                    });
                }
            });
        }
    });
}

Solution

  • Your goal is to put a watch on groupName which lies inside the each Group of Groups object. So your current watcher is pointing to user.Groups.Name which doesn't exist actually. If you want to make your current code working then you could take use on index while putting $watch

    Code

    function SpecController($scope) {
        angular.forEach($scope.user.Groups, function (g,index) { //added index param here
            if (g.Name == "High") {
                alert('You are in the correct group!');
                //used that index param here to put watch on each group.
                $scope.$watch('user.Groups['+ index + '].Name', function (val) { 
                    if (!val) return;
                    if (val == "High") {
                        $scope.Variant.Specs.Color.Options = $scope.Variant.Specs.Color.Options.filter(function (item) {
                            return item.Value !== 'Red' && item.Value !== 'Blue';
                        });
                    }
                });
            }
        });
    }
    

    Note

    This solution would mess when you will have more than 1000 groups in user.Groups, watcher number will increased and resultant would be app will work slowly.