2015-06-22 78 views
1

我正在創建一個活動websocket應用程序,它需要在更改值時抓住用戶的注意力。

以下指令在多個地方使用的同一頁上:

<span class="badge" animate-on-change animate-class="highlightWarning" animate-watch="totalAnswers">{{totalAnswers}}</span> 

<div animate-on-change animate-class="colorWarning" animate-watch="rq.answer" 
           ng-switch="question.type" 
           ng-repeat="rq in recentResponse.answers" 
           ng-if="rq.question == question.id"> 

現在,rq.answer很少改變,但每一次變化的實際值的變化。 IE:它工作正常。

不幸的是,第一次在第一次調用後不工作(在頁面加載時),但{{totalAnswers}}顯示了視覺改變。該模型肯定會更新,但$ watch不會被調用。爲什麼是這樣?

.directive('animateOnChange', function ($timeout) { 
    return { 
     scope: { 
     animateClass: '@', 
     animateTime: '@', 
     animateWatch: '@', 
     animateCollection: '@' 
     }, 
     link: function (scope, element, attr) { 
     function call() { 
      element.addClass(scope.animateClass); 
      $timeout(function() { 
      element.removeClass(scope.animateClass); 
      }, scope.animateTime || 1000); // Could be enhanced to take duration as a parameter 
     } 

     if (scope.animateWatch) 
      scope.$watch(scope.animateWatch, function (nv, ov) { 
      call(); 
      }, true); 
     if (scope.animateCollection) 
      scope.$watchCollection(scope.animateCollection, function (nv, ov) { 
      call(); 
      }); 
     } 
    }; 
    }) 
; 

回答

2

您需要更改的$watch的第一個參數,是一個函數返回的變量,而不是變量本身:

scope.$watch(function() { 
       return scope.animateWatch; }, 
      function (nv, ov) { 
       call(); }, 
      true); 

採取在錶款一看here at the docs

+0

我試過這個,不幸的是這並沒有解決我的問題,因爲Watch的第一個參數也可以帶一個String。無論這種改變已經阻止了TotalAnswers完全工作。 –

+0

@ThomasNairn爲什麼你用'@'而不是'='綁定? –

+0

當我改變你的版本時,我做了,否則我只是pullinh字符串,讓$ watch做實際的綁定。 –