我正在尝试在服务中更改变量,但在控制器中观察不会在发生时触发:

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
.

这里是一个 propunt 为此。原因是什么?

有帮助吗?

解决方案

$手表没有错。$ Watch表达式用于根据调用的范围进行评估,并将字符串表达式或函数作为其第一个参数。要将其工作到Controller内的Publish Account,请通过字符串在其上发布到Scope和$ Watch:

演示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
.

或者或者将手表表达式更改为返回帐户的函数.User.Status属性。我不熟悉咖啡脚本,所以我会把这个例子留给你。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top