将参数传递给Angular中的JS Animation

ilm*_*mgb 6 angularjs

我写了这个包含一个简单JS动画的Plunker,通过jQuery.css/jQuery.animate完成.

简短的介绍:

  • 3个矩形示
  • 按钮"随机化"随机化矩形的宽度/高度
  • widht/height的这种变化应该是动画的

我需要能够将更改的宽度/高度作为参数传递给动画addClass函数.该addClass确定指标如下:

addClass(element, className, doneCallback)
Run Code Online (Sandbox Code Playgroud)

所以我将自定义值添加到元素的原型中.例如LoC 53

Object.getPrototypeOf(element).custom_bs_width = newVal[attrs.id].width;
Run Code Online (Sandbox Code Playgroud)

并在addClass函数中访问它们以进行动画处理.LoC 65+

myApp.animation('.updateRectangles', function() {
return {
    addClass : function(element, className, done) {
      jQuery(element).animate({
        width:  Object.getPrototypeOf(element).custom_bs_width,
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?如果不是,有什么替代方案存在将参数传递给JS动画.我将CSS动画和CSS关键帧动画排除为imho,无法传递参数.同意?

Ber*_*ard 2

正如您所怀疑的,“将参数传递给 addClass”是一个非常扭曲的黑客。

Angular 动画是围绕 CSS 类(因此是 addClass/removeClass)构建的,因此可以很好地与 CSS3 过渡配合使用。该系统的目的是让 ng-repeat 中的 DOM 元素自动设置 CSS 类,以便在添加、移动或删除项目时触发动画。这与“自定义”动画无关,我认为这是您的意图。

一种选择是使用纯 CSS3 转换(与 CSS 动画不同),并通过 ng-style 使用标准 Angular 数据绑定简单地修改元素的大小/位置/颜色。如果在 CSS 中正确设置 CSS 过渡,它将自动启动。我创建了一个简单的方法(computeCSS),将“项目的数据”“转换”为 ng 风格友好的结构。这是代码(还有一个好处是可以平滑地褪色)。

http://plnkr.co/edit/oMOUiV5Sk6YusPpOqUQz?p=preview

添加了 600 毫秒的 CSS3 过渡:

<style>
  .my-rectangles {
    position:absolute;
   -webkit-transition: width 0.6s, height 0.6s, left 0.6s, top 0.6s, background-color 0.6s;
   transition: width 0.6s, height 0.6s, left 0.6s, top 0.6s, background-color 0.6s;
  }
</style>
Run Code Online (Sandbox Code Playgroud)

这是代码:

var myApp = angular.module("MyApp", ["ngAnimate"]);

myApp.controller('MainCtrl', function($scope) {
  //nothing to declare
});

//general directive for the rectangles
myApp.directive('rectangles', function() {
  return{
    restrict: 'E',
    template: '<div style="position:relative; width: 200px; height: 200px; background-color: #646464">' +
                  '<div ng-repeat="item in items" id="{{$index}}" class="my-rectangles" ng-style="computeCSS(item)"></div>' +
              '</div>',
    controller: function($scope) {

      $scope.computeCSS = function(item) {
        return { 
          width: item.width+"px", 
          left: item.left+"px", 
          top: item.top+"px", 
          height: item.height+"px", 
          'background-color':item.color
        };
      }

      $scope.items = [
        {width: 10, left: 10, top: 10, height: 10, color:'#4C8B71'},
        {width: 10, left: 80, top: 10, height: 10, color:'#F3D698'},
        {width: 10, left: 160, top: 10, height: 10, color:'#D25F45'}
      ];

      $scope.randomize = function() {
        $scope.items.forEach(function(item) {
          item.width = Math.random() * (40 - 10) + 10;
          item.height = item.width;
          item.color = "#" + (Math.round(Math.random()*0xFFFFFF)).toString(16);
        })
      }
    }
  }    
});
Run Code Online (Sandbox Code Playgroud)