javascript - 无法使用动态键更改 AngularJS 模型对象值

标签 javascript angularjs

app.controller('indexController', ['$scope', '$location', 'authService', function ($scope, $location, authService) {

    var vm = this;
    vm.$onInit = function () {
        vm.active = {
            "home": true,
            "welcome": false,
            "user": false,
            "logout": false,
            "login": false,
            "signup":false
        };
    };

    $scope.$watch('vm.active', function (newObj, oldObj) {
        Object.keys(newObj).filter(function (key) {
            vm.active[key] = newObj[key] !== oldObj[key];
            return vm.active[key];
        });
    }, true);

}]);

我在这里尝试更改 vm.active 对象属性,但它显示以下错误:

angular.js:14642 Error: [$rootScope:infdig]http://errors.angularjs.org/1.6.5/$rootScope/.. at angular.js:88 at m.$digest (angular.js:18248) at b.$apply (angular.js:18480) at HTMLAnchorElement. (angular.js:27290) at HTMLAnchorElement.dispatch (jquery-3.1.1.js:5201) at HTMLAnchorElement.elemData.handle (jquery-3.1.1.js:5009)

最佳答案

它显示错误是因为您的代码导致无限 $digest 循环,因为您试图在摘要循环期间更改模型。

要解决此问题,请避免使用 $watch 更改模型。

关于javascript - 无法使用动态键更改 AngularJS 模型对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45704075/

相关文章:

javascript - Eslint 未定义导入问题

javascript - 常见问题 切换 div 显示/隐藏 + 更改链接文本

javascript - 为什么我在浏览器中收到 {}.toString() 的意外 token 错误,但在 Node 中却没有?

javascript - Angular-UI $scope.myMap 未定义

javascript - 如何获取“检查元素”中显示的网站数据,而不是“查看页面源”中显示的网站数据?

javascript - AngularJS - 在回调中包含变量

javascript - 如何使用 angularjs 打开新的浏览器实例而不是选项卡

angularjs - 在 Angular 中禁用/删除 http 拦截器的正确方法?

javascript - 文本区域字符串 : limit to 1 empty line at a time

javascript - 对象不支持 IE 10 中的属性或方法 'querySelector'