سؤال

أحاول تغيير المتغير في الخدمة ولكن المراقبة في وحدة التحكم لا يتم تشغيلها عند حدوث ذلك:

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

هنا أ غطس لهذا.ماهو السبب؟

هل كانت مفيدة؟

المحلول

لا يوجد شيء خاطئ في $watch.يتم تقييم تعبير $watch مقابل النطاق الذي يتم استدعاؤه عليه ويأخذ تعبير سلسلة أو دالة كوسيطة أولى له.لجعله يعمل إما النشر Account داخل وحدة التحكم الخاصة بك للنطاق ومشاهدتها $ عبر السلسلة:

الغطاس التجريبي

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