3

I have an audio element in my service that has a "ended" event listener. I'm trying to communicate that message to an angular controller.

Currently I have this in my service:

Audio.addEventListener "ended", (->
      $rootScope.$broadcast("audioEnded")
    ), false

And in my controller I have:

$scope.$on "audioEnded", ->
      console.log("ended scope")

This works but I'm wondering if there is a better way to communicate from a service to a controller without using $rootScope

4

1 回答 1

3

实现您想要的常用方法是将事件聚合器实现为服务。您可以通过简单的依赖注入在任何指令、控制器或配置函数中使用它。

app.service 'vent', ->
    handlers: []
    on: (eventName, handler) ->
       #register handler
    emit: (eventName, args...) ->
       #iterate events and call registered handlers

使用示例:

app.controller 'Ctrl', (vent) ->
    vent.on 'eventname', ->
        #...
    vent.emit 'eventname'
于 2013-07-28T16:07:34.063 回答