繁体   English   中英

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

[英]AngularJS scope.$watch in directive isn't raised

我希望使用$ 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值时,手表什么都不做。 我的指令不是那么强,谁能告诉我哪里出错了。

提前致谢。

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

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

暂无
暂无

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

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