Javascript $emit 或 $broadcast 从控制器到指令 AngularJS 的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25878077/
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
$emit or $broadcast an event from a controller to a directive AngularJS
提问by user1876246
I want to be able to notify a directive when an event happens to change what the directive displays. I know that directives only run once, so I am wondering how I would go about doing this. I am also not sure if I should use $emit or $broadcast, is a directive a child of the controller?
我希望能够在事件发生更改指令显示的内容时通知指令。我知道指令只运行一次,所以我想知道我将如何做到这一点。我也不确定是否应该使用 $emit 或 $broadcast,指令是控制器的子指令吗?
For example, in my controller I have:
例如,在我的控制器中,我有:
$rootScope.$emit('PHOTO_UPLOADED', photo);
$rootScope.$emit('PHOTO_UPLOADED', photo);
And in my directive:
在我的指令中:
.directive('photo', [function () {
return {
restrict: 'EA',
scope: {user: '='},
replace: true,
template: '<div id="{{user.id}}"></div>',
link: function ($scope, element, attrs) {
var thumbnail = ($scope.user && $scope.user.image)
? $scope.user.image
: '/default.png';
element.css('background-image', 'url(' + thumbnail + ')');
$rootScope.$on('PHOTO_UPLOADED', function(event, data) {
thumbnail = data;
});
}
};
}])
I tried to do this but nothing happened, the thumbnail was not updated because the directive already ran.
我试图这样做,但什么也没发生,缩略图没有更新,因为指令已经运行。
回答by sma
Use $broadcast. That will broadcast events to child scopes. Here is an example of using broadcast to send data to a directive from a parent controller:
使用$broadcast. 这将向子作用域广播事件。以下是使用广播将数据从父控制器发送到指令的示例:
回答by raga
In your controller do:
在您的控制器中执行以下操作:
$rootScope.$broadcast('PHOTO_UPLOADED', photo);
and in your directive, catch the broadcast event via
并在您的指令中,通过以下方式捕获广播事件
$rootScope.$on('PHOTO_UPLOADED', function(event, data) {
thumbnail = data;
});
回答by Mike Driver
You need to make sure to pass $rootScopeto your directive so it can be injected:
您需要确保传递$rootScope给您的指令,以便它可以被注入:
.directive('photo', ['$rootScope', function($rootScope) {
// snip
}]);
Modify you code's first line to the above and it should work fine.
将代码的第一行修改为上述内容,它应该可以正常工作。

