5

我有以下代码,

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-ed 到作用域级别。现在的问题是,我在 a 中接收广播directive,当我控制台e或时scope,我可以看到module其中有一个包含数据的数组,而当我控制台时scope.module,它说[]。我没有收到错误,我做错了什么吗?

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

提前致谢

4

1 回答 1

6

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

scope.$digest();

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

于 2013-11-12T12:55:24.310 回答