javascript AngularJS 指令 - 从 $rootscope 接收广播

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19929074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:16:51  来源:igfitidea点击:

AngularJS Directive - Receiving a broadcast from $rootscope

javascriptangularjsangularjs-directiveangularjs-scope

提问by moustacheman

I have the following code,

我有以下代码,

HTML

HTML

<div ng-app="test">
    <div ng-controller="containerCtrl">
        <component data-module="components"></component>
    </div>
</div>

JS

JS

var test = angular.module('test', []);

test.controller('containerCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
    $scope.components = [];
    $scope.$on('onSomething', function(e) {
        $scope.components = $rootScope.config;
    });
}]);

test.directive('component', function () {
        var linkFn = function(scope, element, attrs) {
            scope.$on('onSomething', function(e) {
                console.log(scope, e, scope.module, e.currentScope.module);
                /*
                * Here 'module' is an array in both 'e' and 'scope' , but when I console it says [].
                */
                console.log("onSomething!");
            });
        };

        return {
            restrict: 'E',
            scope: {
                module: '=module'
            },
            link : linkFn
        };
    });

test.run(['$rootScope', '$timeout', function ($rootScope, $timeout) {
    $timeout(function(){
        $rootScope.config = [{id: "c1", width: 100, height: 100 }];
        $rootScope.$broadcast("onSomething", "");
    },5000);

}]);

Fiddlehttp://jsfiddle.net/vFncP/4/

小提琴http://jsfiddle.net/vFncP/4/

ProblemIn runmethod, I have an ajax request which receives a configuration from the database. Once the request is complete, It is broadcast-ed to the scope level. Now the problem is, I am receiving the broadcast in a directive, when I console eor scope, I can see the modulewhich has an array with data whereas when I console scope.module, it says []. I am not getting the error, am I doing something wrong?

问题run方法中,我有一个从数据库接收配置的 ajax 请求。请求完成后,它会broadcast进入范围级别。现在的问题是,我在 a 中接收广播directive,当我控制台e或时scope,我可以看到module其中有一个包含数据的数组,而当我控制台时scope.module,它显示[]. 我没有收到错误,我做错了什么吗?

Note:Adding a $scope.$watchmight help, but I am trying to avoid $watch. Is there any other way to do it.

注意:添加一个$scope.$watch可能会有所帮助,但我试图避免$watch. 有没有其他方法可以做到。

Thanks in advance

提前致谢

回答by Anthonny

A solution could be $digest to refresh scope values:

解决方案可能是 $digest 刷新范围值:

scope.$digest();

http://jsfiddle.net/Anthonny/vFncP/7/

http://jsfiddle.net/Anthonny/vFncP/7/