简体   繁体   English

AngularJS-$ 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. 如果用户是我的商店站点上“高级”组的成员,我试图删除产品SKU上的“红色”和“蓝色”下拉列表选项。 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';
                    });
                }
            });
        }
    });
}

Your goal is to put a watch on groupName which lies inside the each Group of Groups object. 您的目标是监视每个Group of Groups对象内的groupName So your current watcher is pointing to user.Groups.Name which doesn't exist actually. 因此,您当前的观察者指向的是user.Groups.Name ,它实际上并不存在。 If you want to make your current code working then you could take use on index while putting $watch 如果要使当前代码正常工作,则可以在放置$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. 当用户中有1000个以上的groups时,此解决方案将变得混乱user.Groups观察者数量将增加,从而导致应用程序运行缓慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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