AngularJS,更改动画:未调用指令$watch

AngularJS, Animate on change: directive $watch not called

本文关键字:调用 指令 watch 动画 AngularJS      更新时间:2023-09-26

我正在创建一个实时的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();
          });
      }
    };
  })
;

您需要更改$watch上的第一个参数,使其成为返回变量的函数,而不是变量本身:

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

请看一下手表部分的文档。