Angular的$scope变量在通过$rootScope.$on调用后没有更新



我有一个全局方法,用于在整个应用程序中监视按键。当按键发生时,我像这样广播事件:

var keycodes = {
    'escape': 27,
}
angular.element($window).on('keydown', function(e) {
    for (var name in keycodes) {
        if (e.keyCode === keycodes[name]) {
            $rootScope.$broadcast('keydown-' + name, angular.element(e.target))
        }
    }
})

这一切都很好。在我的控制器中,我像这样监听事件:

$rootScope.$on('keydown-escape', $scope.hideOverlays)

这也可以正常工作,但是,当我尝试更新$scope对象上的属性时,我在DOM中看不到正确的行为:

 $scope.hideOverlays = function() {
        for (var i=0; i < $scope.gallery.items.length; i++) {
            $scope.gallery.items[i].overlayShown = false;
            $scope.gallery.items[i].editing = false;
        }
    }

当我从控制器内部调用这个方法时,一切都很好,所以我想知道Angular是否会根据调用方法的方式做一些不同的事情。我试过调用$scope.$apply()。除了看起来不正确之外,我还会得到一个错误,所以这里没有骰子。任何帮助都非常感谢!

有很多缺失的代码带来了一些问题,例如,你在哪里执行你的keydown事件,在我的例子中,你会看到我已经把它放在了app.run在Angular:

// Note you have to inject $rootScope and $window
app.run(function ($rootScope, $window) {
    angular.element($window).on('keydown', function (e) {
        for (var name in keycodes) {
            if (e.keyCode === keycodes[name]) {
                $rootScope.$broadcast('keydown-' + name, angular.element(e.target))
            }
        }
    })
});

这允许它在加载任何控制器之前执行。


然后在你的控制器,而不是运行$scope.$apply,你应该做一个"安全"的$范围。$apply方法检查是否存在摘要或应用阶段,如果存在则不应用,否则可以。

// Again make sure that you have everything you need injected properly.
// I need $rootScope injected so I can check the broadcast
app.controller('MainCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
    $scope.hello = "Hello World";
    var count = 0;
    $scope.hideOverlays = function () {
        count++;
        $scope.safeApply(function () {
            $scope.hello = "You pressed the escape key " + count + " times.";
        });
    };
    $rootScope.$on('keydown-escape', $scope.hideOverlays);
    $scope.safeApply = function (fn) {
        var phase = this.$root.$$phase;
        // If AngularJS is currently in the digest or apply phase
        // we will just invoke the function passed in
        if (phase == '$apply' || phase == '$digest') {
            // Let's check to make sure a function was passed
            if (fn && (typeof (fn) === 'function')) {
                // Invoke the function passed in
                fn();
            }
        } else {
            // If there is no apply or digest in the phase
            // we will just call $scope.$apply
            this.$apply(fn);
        }
    };
}]);

这是一个显示当按下转义键

时DOM更新的工作小提琴

最新更新