Angularjs,观察rootScope变量,通过动画不起作用来做出反应

时间:2014-06-01 19:07:56

标签: angularjs

您好我的application.js ...

中有以下代码段
.directive('titleEffect', function($animate){
    return function(scope, element, attrs){
        scope.$watch(attrs.titleEffect, function(newVal){
            $animate.addClass(element, 'title_effect')
        })
    };

})

.animation('.title_effect', function(){
    return{
        addClass: function(element, className){
            console.log('aaa')
        }
})

但是没有触发ng-animation addClass函数,这是我的html:

<h3  title-effect='globalData.currentTitle' > </h3>

其中currentTitle是一个全局数据集:

.run(function($rootScope){
$rootScope.globalData = {currentTitle : ''}
})

1 个答案:

答案 0 :(得分:0)

在指令准备好之前,您的监视功能可能会被调用2次。使用您的代码,.title_effect类已添加,但未添加动画,因为它是在初始化之前添加的,您从未删除过类。您还需要在动画中调用done(),以便从元素中移除ng-animate,以便更改动画。

&#13;
&#13;
var app = angular.module("app", ["ngAnimate"])

.controller('MainCtrl', function() {
  var vm = this;
  vm.titleEffect = false;
})

.directive("titleEffect", ["$animate",
  function($animate) {
    return function(scope, element, attrs) {
      scope.$watch(attrs.titleEffect, function(newValue) {
        if (newValue) {
          $animate.addClass(element, "title_effect");
        } else {
          $animate.removeClass(element, "title_effect");
        }
      });
    };
  }
])

.animation(".title_effect", function() {
  return {
    addClass: function(element, className, done) {
      console.log('add');
      TweenMax.to(element, 0.35, {
        autoAlpha: 0,
        onComplete: done
      });
    },
    removeClass: function(element, className, done) {
      console.log('remove');
      TweenMax.to(element, 0.35, {
        autoAlpha: 1,
        onComplete: done
      });
    }
  };
});
&#13;
.block {
  width: 500px;
  height: 100px;
  background-color: black;
  margin-top: 25px;
}
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.13.2/TweenMax.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-animate.min.js"></script>

<div ng-app="app" ng-controller="MainCtrl as vm">
  <button ng-click="vm.titleEffect = !vm.titleEffect">Toggle</button>
  <div class="block" title-effect="vm.titleEffect"></div>
</div>
&#13;
&#13;
&#13;