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
AngularJS Directive - Receiving a broadcast from $rootscope
提问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 run
method, 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 e
or scope
, I can see the module
which 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.$watch
might 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();