简体   繁体   English

AngularJS,对变化进行动画处理:未调用指令$ watch

[英]AngularJS, Animate on change: directive $watch not called

I'm creating a live websocket application which requires grabbing the users attention upon change of a value. 我正在创建一个实时的websocket应用程序,该应用程序需要在更改值时吸引用户的注意力。

The following directive is used in multiple places on the same page: 在同一页面的多个位置使用以下伪指令:

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

and

<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">

Now, rq.answer rarely changes, but changes every time the actual value changes. 现在,rq.answer很少更改,但是每次实际值更改时都会更改。 IE: it works correctly. IE:它正常工作。

Unfortunately the first one does not work after the first call (On page load) but the {{totalAnswers}} shows the visual change. 不幸的是,第一个调用在第一次调用(页面加载)后不起作用,但是{{totalAnswers}}显示了外观变化。 The model definitely updates but the $watch is not called on it. 该模型肯定会更新,但不会调用$ watch。 Why is this? 为什么是这样?

.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();
          });
      }
    };
  })
;

You need to change the first argument on the $watch , to be a function returning your variable, instead of the variable itself: 您需要将$watch上的第一个参数更改为返回变量的函数,而不是变量本身:

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

Take a look here at the docs at the watch section. 在观看部分的文档中查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM