我有以下代码,
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
收到广播,当我控制e
或scope
时,我可以看到module
有数据的数组,而当我控制scope.module
,它说[]
。我没有收到错误,我做错了什么?
注意:添加$scope.$watch
可能有所帮助,但我正在努力避免$watch
。还有其他办法吗。
提前致谢