Javascript 如何在 Angularjs 中广播对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12662258/
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
How can I broadcast an object in Angularjs?
提问by user1703761
How can I broadcast an object through an event?
如何通过事件广播对象?
Currently I am trying:
目前我正在尝试:
app.run ($rootScope) ->
message = {type: 'channel', action: 'create', data: { name: "ssss", id: 0}}
$rootScope.$broadcast('message', message)
angular.module('WebChat').controller 'ChannelController', ($scope) ->
$scope.$on 'message', (message) ->
console.log message
console.log 'hi'
But I am getting no output
但我没有输出
EditI got it working. It seems that the first parameter of the callback function is the scope. I had to change the controller to:
编辑我让它工作。看来回调函数的第一个参数是作用域。我不得不将控制器更改为:
angular.module('WebChat').controller 'ChannelController', ($scope) ->
$scope.$on 'message', (scope, message) ->
console.log message
console.log 'hi'
采纳答案by pkozlowski.opensource
You are getting no output in your case since you are broadcasting before a controller is ready to accept messages. The module's run method is executed very early in the application's life-cycle, before controller's scopes are ready to listen to messages.
由于您在控制器准备好接受消息之前进行广播,因此您的案例没有任何输出。模块的 run 方法在应用程序生命周期的早期执行,在控制器的作用域准备好侦听消息之前。
Here is the jsFiddle that illustrates this, check the console to see that broadcast happens before a listener is ready: http://jsfiddle.net/vPq2P/3/
这是说明这一点的 jsFiddle,检查控制台以查看广播是否在侦听器准备就绪之前发生:http: //jsfiddle.net/vPq2P/3/