为什么不添加ng-leave / ng-enter类

时间:2016-01-14 17:35:06

标签: javascript angularjs

根据角度文档 https://docs.angularjs.org/api/ng/directive/ngRepeat#animations

  

" .enter - 将新项目添加到列表或项目时   在过滤器后显示

     

.leave - 从列表中删除项目或项目时   过滤掉了#34;

然而,当我从数组中获取.push({})或.splice(-1,1)时,这些类都没有添加到ng-repeat中。问题是什么?

<div ng-controller="MyCtrl">
   <button ng-click="addLine()">
     add
   </button>
   <button ng-click="removeLine()">
     remove
   </button>
  <div ng-repeat="line in lines">
      <div class="preview">{{$index}}</div>
   </div>
</div>
var myApp = angular.module('myApp', ['ngAnimate']);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
        $scope.addLine = function(){
        $scope.lines.push({})
    }
    $scope.removeLine = function(){
        $scope.lines.splice(-1, 1)
    }
    $scope.lines = [{
        text: 'res1'},
    {
        text: 'res2'}];
}

正如Ted在他的回答中指出的那样,需要.ng-enter / .ng-leave的实际css样式,否则ngAnimate模块不会将.ng-enter类添加到DOM元素

更清楚的是,我现在并不关心实际制作动画。这里的问题是.ng-enter类实际上并没有应用于元素的class属性,除非你有.ng-enter的css样式

工作PLUNKER http://plnkr.co/edit/TqpdIy6syikBhAeb5Kw3?p=preview

1 个答案:

答案 0 :(得分:5)

要添加这些类,您必须在应用中加载动画模块。

有关如何执行此操作,请参阅the ngAnimate docs

首先,您必须加载附加模块的.js文件:

<script src="angular.js">
<script src="angular-animate.js">

然后将其列为应用程序的依赖模块:

angular.module('app', ['ngAnimate']);

ngAnimate模块也要求元素在CSS或JS中定义其转换:

  

对于CSS转换,必须在起始CSS类中定义转换代码(在本例中为.ng-enter)。目标类是转换将动画化的目标。

如果您添加以下内容:

/* The starting CSS styles for the enter animation */
.fade.ng-enter {
  transition:0.5s linear all;
  opacity:0;
}

/* The finishing CSS styles for the enter animation */
.fade.ng-enter.ng-enter-active {
  opacity:1;
}

它应该开始工作了。

非常清楚,因为文档没有明确说明:如果动画没有在CSS或JS中定义,ngAnimate模块甚至不会添加类,它只会跳过所有动画在一起。

相关问题