watch does not trigger when service variable updated
-
20-12-2019 - |
Question
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?
Solution
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:
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow