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

tri*_*tty 5 javascript angularjs

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

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

.leave - 从列表中删除项目或过滤项目时"

但是,当我从数组中获取.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'}];
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ted*_* A. 5

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

有关如何执行此操作,请参阅ngAnimate文档.

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

<script src="angular.js">
<script src="angular-animate.js">
Run Code Online (Sandbox Code Playgroud)

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

angular.module('app', ['ngAnimate']);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

它应该开始工作.

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