0

I'm trying to change variable in service but watch in controller does not trigger when that happens:

app.factory 'User',  ->
  class User
    status: 'offline'
    set_status: (status) ->
      @status = status

app.service 'Account', ->
  dsa: null
  test: 'asd'
  user: null

app.controller 'MainCtrl', ($scope, $timeout, Account, User) ->
  Account.user = new User
  $scope.$watch Account.user.status, (status) ->
    console.log "status changed to #{status}"

  $timeout ->
    Account.user.set_status 'busy'
    console.log Account.user.status
  , 2000

Here is a plunk for this. What is the reason?

SET
  • 10,274
  • 4
  • 42
  • 70
  • Have a look at this answer for the correct approach in this kind of scenario: http://stackoverflow.com/questions/12576798/angularjs-how-to-watch-service-variables – Mimo Apr 10 '14 at 22:42
  • @maurizio There's nothing wrong with using $watch, no need to go the observer pattern unless it really is necessary. – Beyers Apr 10 '14 at 22:49
  • @maurizio, I also don't like idea of using observer but in my case there is definitely something wrong with $watch – SET Apr 10 '14 at 22:56

1 Answers1

1

There's nothing wrong with $watch. The $watch expression is evaluated against the scope it is called on and takes a string expression or a function as its first argument. To get it to work either publish Account inside your controller to scope and $watch on it via string:

Demo plunker

app.controller 'MainCtrl', ($scope, $timeout, Account, User) ->
  $scope.name = 'World'
  console.log Account
  Account.user = new User
  $scope.Account = Account
  $scope.$watch 'Account.user.status', (status) ->
    console.log "status changed to #{status}"

  $timeout ->
    Account.user.set_status 'busy'
    console.log Account.user.status
  , 2000

Or alternatively change the watch expression to a function that returns your Account.user.status property. I'm not familiar with coffee script so I'll leave the example up to you.

Beyers
  • 8,555
  • 39
  • 51
  • Thanx man. I thought I can use it without exposing the service variables to the scope and that was my mistake.... – SET Apr 10 '14 at 23:24