AngularJS - Trouble with $watch

AngularJS - Trouble with $watch

本文关键字:watch with Trouble AngularJS      更新时间:2023-09-26

如果用户是我的商店网站上"高"组的成员,我正在尝试删除产品 SKU 上的"红色"和"蓝色"下拉列表选项。我想出的代码如下,但只能部分工作;唯一有效的是窗口警报。现在,如果我删除有关查找用户组的逻辑,那么它确实有效,但是用户必须首先设置颜色下拉列表的值。

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

你的目标是在Groups物体的每个Group内的groupName上放一块手表。因此,您当前的观察者指向实际上不存在user.Groups.Name。如果你想让你当前的代码工作,那么你可以在放置$watch时使用索引

法典

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

注意

当您拥有超过 1000 groups时,此解决方案会搞砸 user.Groups,观察者数量将增加,结果将是 应用程序将运行缓慢。