3

Ok, I'm really struggling with this one. I looked everywhere I could for a solution but didn't find it even though there are quite a few similar questions.

I have a class. I need only one instance, so I made service for it:

services.factory('PlayerService', ->
     new Player()
)

As you can see it is some kind of player. I need my view to update when the song changes.

Here is an extremely simplified demo plnk that exposes the problem: http://plnkr.co/edit/L3WndT

And here is what I tried based on this question. None of solutions work.

View

<div ng-controller="PlayerController">
    {{ player.currentSong }}
</div>

First one

PlayerController = ($scope, PlayerService) ->
    $scope.player = PlayerService
    return

Second one

PlayerController = ($scope, PlayerService) ->
    $scope.$watch(
        'myApp.services.PlayerService'
        (newval, oldval) ->
            $scope.currentSong = newval
        true
    )
    return
Community
  • 1
  • 1
  • I think this response is exactly what you need : http://stackoverflow.com/a/10180805/34871 For a better understanding, see the Scope Life Cycle in the developer guide: http://docs.angularjs.org/guide/scope – vincent Apr 14 '13 at 00:42

1 Answers1

0

If you are really dealing with some external service that updates periodically and doesn't provide any way to listen for update events (as illustrated in your Plunker), you could poll for updates and keep the scope in sync like so:

http://plnkr.co/edit/PJpQ2a?p=preview

Note that the poll method doesn't need to explicitly update the scope. Angular has created a watch on the expression 'serviceClass.prop' that you embedded in the view. The $timeout service triggers a digest cycle, which fires the watch listener when the expression changes and updates the view.

karlgold
  • 7,857
  • 2
  • 27
  • 22