AngularJS范围。$ watch in指令不会引发

时间:2015-03-02 16:57:49

标签: javascript css angularjs

我希望使用$ animate库来应用一些CSS类,并且在我的指令中我希望在css动画完成后切换范围变量值。我希望使用ng-show指令显示DIV,当满足此条件时(scope.showPopover === true)我希望显示该项目然后它必须逐渐消失。我有一个自定义指令来执行CSS淡入淡出并重置ng-show的条件...这里是我的代码

<!-- here is the popover, the showPopover and popoverNeeded scope variables are in my controller  -->
<div data-ng-if="popoverNeeded === true" class="nav-popover" data-fade-animation data-ng-show="showPopover">
  I am a popover that will toggle, then fade away....
</div>

这是我的控制器变量......

$scope.popoverNeeded = true;
$scope.showPopover = false;

这是我的自定义指令

.directive('fadeAnimation', function ($animate) {
        'use strict';
        return {
            restrict: 'A',
            priority: 800,
            link: function (scope, element) {

                console.log(scope.showPopover); // false

                scope.$watch(scope.showPopover, function (newValue, oldValue) {

                    console.log(newValue, oldValue); // undefined undefined

                    if(newValue === true) {
                        $animate.addClass(element, 'fade-animiate').then(function() {
                            element.removeClass('fade-animiate');
                            scope.showPopover = false;
                        });
                    }

                });
            }
        };
    });

这是我的css ......

.fade-animiate {
  animation: fade-animiate 2s;
  -webkit-animation: fade-animiate 2s;
  animation-fill-mode: forwards;

  animation-delay: 5s;
  -webkit-animation-delay: 5s; /* Safari and Chrome */
  -webkit-animation-fill-mode: forwards;
}


@keyframes fade-animiate {
  from {
    opacity: 1;
    display: block;
  }
  to {
    opacity: 0;
    display: none;
  }

}

@-webkit-keyframes fade-animiate {
  from {
    opacity: 1;
    display: block;
  }
  to {
    opacity: 0;
    display: none;
  }

}

现在,当视图/页面加载scope.showPopover值时输出并且是正确的,我们在控制台中看到false。监视值输出为undefined, undefined。但是当我切换scope.showPopover值时,手表什么都不做。我的指令不是那么强,谁能告诉我哪里出错了。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您不要在$watch中使用scope作为前缀(它还需要一个字符串供var观看):

scope.$watch("showPopover", function (newValue, oldValue) {