如何在Angularjs中广播对象?

时间:2012-09-30 15:05:45

标签: javascript angularjs

如何通过活动广播对象?

目前我正在尝试:

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'

但我没有输出

修改 我搞定了。似乎回调函数的第一个参数是范围。我不得不将控制器更改为:

angular.module('WebChat').controller 'ChannelController', ($scope) -> 
    $scope.$on 'message', (scope, message) ->
        console.log message
        console.log 'hi'

1 个答案:

答案 0 :(得分:7)

由于您在控制器准备接受消息之前广播,因此您的案例中没有输出。在控制器的作用域准备好收听消息之前,模块的run方法在应用程序的生命周期的早期执行。

这是说明这一点的jsFiddle,检查控制台,看看广播是在听众准备好之前发生的:http://jsfiddle.net/vPq2P/3/

相关问题