【问题标题】:AngularJS animation when model changes模型更改时的AngularJS动画
【发布时间】:2015-04-04 05:52:35
【问题描述】:

我一直在 Google 和 Stackoverflow 上搜索,但没有找到我要找的东西。

这就是我所拥有的。我保证我会真诚地努力解决这个问题。

问题如下:我有动画处理列表。当我使用超时将项目添加到列表中时,它们会正确地动画化。但是,“title”变量是一个字符串。我想在此值更改时应用动画。老实说,我现在仍然对如何让它发挥作用一无所知。我知道我可以为 ng-hide 的动画添加 css 类,但我仍然不太明白如何在这里适应它。提前感谢任何帮助。请赐教。你不必给我代码。即使是对如何实现这一点的高级描述也足够了。

// app.js
(function() {
  var app = angular.module("MyApp", ["ngAnimate"]);
  // route configuration
}());

// homecontroller.js
(function() {
  var app = angular.module("MyApp");
  app.controller("HomeController", ["$scope","$timeout", homeController];

  function homeController($scope, $timeout) {
    $scope.items = ["Frodo", "Bilbo", "Merry", "Pippin", "Sam"];
    $scope.title = "The Hobbits";

    $timeout(function() {
      $scope.title = "The Hobbits and the Wizard";
      $scope.items.unshift("Aragorn","Faramir","Boromir");
    }, 5000);
  }
}());

一些 HTML

<!-- view for HomeController -->
<h1>{{ title }}</h1>
<div ng-controller="HeaderWebpart.HeaderController">
  <div class="testClass" style="display:block;" ng-repeat="item in items">{{ item }}</div>
</div>

还有 CSS

div.testClass.ng-enter {
  -webkit-animation: enter 1000ms cubic-bezier(0.250, 0.100, 0.250, 1.000);
  animation: enter 1000ms cubic-bezier(0.250, 0.100, 0.250, 1.000);
  display: block;
  position: relative;
}
@-webkit-keyframes enter {
    from {
      opacity: 0;
      height: 0px;
      left: -70px;
    }
    75% {
      left: 15px;
    }
    to {
      opacity: 1;
      height: 20px;
      left: 0px;
    }
}
div.testClass.ng-enter-active {
    opacity: 1;
}

【问题讨论】:

  • 此站点可能会有所帮助:daneden.github.io/animate.css。如您所见,实际动画运行时有一个.animate 类。此外,还可以添加一个 .infinite 类以不断重复动画(不超过设定的时间)。
  • 感谢您发布此信息 - 非常有帮助。

标签: javascript css angularjs animation


【解决方案1】:

您目前没有将任何动画逻辑应用于&lt;h1&gt; 元素,仅在控制器中为title 分配一个值是不够的。

如果您查看角度动画的文档 https://docs.angularjs.org/api/ngAnimate - 你会看到只有一组特定的指令有动画钩子。这些指令中的每一个通常都有一对进入/离开或添加/删除动画。这意味着 Angular 向这些元素添加和删除特定的 CSS 类,您可以使用它们来执行动画,类似于您已经使用上面的 ng-repeat 指令和 testClass 动画完成的操作:

.yourAnimationCSSClass.ng-enter { }
   => what your element should look like before the animation starts
      what the change should be and the duration

.yourAnimationCSSClass.ng-enter.ng-enter-active { }
   => ending(stable) state for your animation, ie. what the 
      element should look like when you're done

...ng-leaveng-leave-active 的工作方式类似。

因此,要为您的 &lt;h1&gt; 元素解决此问题,应用动画的一种方法是使用 ngClass 选择性地设置 CSS 类。这最终与 Angular 开发人员动画指南中的 Class and ngClass animation hooks 示例非常接近,因此请查看该示例。

【讨论】:

  • 通常可以对你的元素做一些小的模板魔法,比如ngClass=" title != '' ? 'myAnimationCSSClass' : '' "ngIf="title != ''"ngShow="title != ''",让你的代码更简洁一些,或者如果你已经使用了不同的动画钩子有一些定义,但每个人可能不喜欢这种方法。但是,其中任何一个都应该允许您只写入控制器中的范围变量并应用动画而无需手动触发它。
  • orbitbot - 感谢您的回复。将此与其他人所说的结合使用。干杯。 :D
猜你喜欢
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
相关资源
最近更新 更多