【问题标题】:AngularJS - Trouble with $watchAngularJS - $watch 的问题
【发布时间】:2015-07-05 20:26:24
【问题描述】:

如果用户是我商店网站上“高”组的成员,我正在尝试删除产品 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';
                    });
                }
            });
        }
    });
}

【问题讨论】:

    标签: javascript angularjs for-loop angularjs-watch


    【解决方案1】:

    您的目标是监视groupName,它位于Groups 对象的每个Group 内。所以你当前的观察者指向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,观察者数量将增加,结果将是 应用会运行缓慢。

    【讨论】:

    • 啊,是的,它是这么写的:TypeError: Cannot read property 'Specs' of undefined at Object.eval [as fn] (eval at <anonymous> (https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js:2:2533), <anonymous>:9:35) at h.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:106:71) at h.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:108:370)
    • @John 我什么都看不见
    • @John 你能告诉我你的$scope.user.Groups 对象是什么样子的
    • 这里是输出:[{"ID":"RQMMyxWC0wqCDjGwqdtTBQ-e-e","InteropID":"","Name":"High","Description":"","IsApprovalGroup":false,"IsReportingGroup":true}]
    • @John $scope.user.Groups 可以有多个组吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 2013-05-26
    相关资源
    最近更新 更多