AngularJS指令 - 从$ rootscope接收广播

时间:2013-11-12 12:22:47

标签: javascript angularjs angularjs-directive angularjs-scope

我有以下代码,

HTML

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

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

}]);

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

问题run方法中,我有一个ajax请求,它从数据库接收配置。请求完成后,broadcast - 范围级别。现在问题是,我正在directive收到广播,当我控制escope时,我可以看到module有数据的数组,而当我控制scope.module,它说[]。我没有收到错误,我做错了什么?

注意:添加$scope.$watch可能有所帮助,但我正在努力避免$watch。还有其他办法吗。

提前致谢

1 个答案:

答案 0 :(得分:6)

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

scope.$digest();

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