質問

私はサービスで変数を変更しようとしていますが、それが起こるときにコントローラ内の時計はトリガーされません:

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
.

これは plunk です。理由は何ですか?

役に立ちましたか?

解決

$ watchに問題はありません。$ Watch式は、それが呼び出されたスコープに対して評価され、文字列式または最初の引数として関数を取ります。機能するように機能するには、コントローラ内のAccountを使用して、Stringを介してスコープと$ 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
.

またはAccount.User.Statusプロパティを返す関数に監視式を変更します。私はコーヒースクリプトに慣れていないので、その例をあなた次第に任せます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top