2014-01-10 109 views
6

我写了这个this Plunker包含一个简单的JS动画,通过jQuery.css/jQuery.animate完成。将参数传递给JS Animation in Angular

简要说明:

  • 3矩形
  • 按钮 “随机化”随机化宽度/高度的矩形
  • 这种变化widht /高度应动画

我需要能够将变化的宽度/高度作为参数传递给动画addClass函数。该addClass确定指标看起来是这样的:

addClass(element, className, doneCallback) 

所以我说我的自定义值元素的原型。例如LoC 53

Object.getPrototypeOf(element).custom_bs_width = newVal[attrs.id].width; 

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

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

这是正确的方法吗?如果不是,替代存在将参数传递给JS动画。 我排除了CSS动画和CSS关键帧动画,因为没有办法传递参数。 同意?

+0

即使使用'element.attr.custom_bs_width =的newval [attrs.id] .WIDTH ;'工作。但仍然 - 这是要走的路吗? – ilmgb

回答

2

正如你怀疑的,“传递参数到addClass”是一个真正扭曲的黑客。

角度动画是围绕CSS类(因此,addClass/removeClass)构建的,因此,与CSS3转换效果很好。这个系统是为了使ng-repeat中的DOM元素自动设置CSS类来触发添加,移动或删除项目时的动画。这与“自定义”动画无关,就像我认为你的意图在这里。

一种选择是使用纯CSS3过渡(这是不一样的CSS动画)和简单地使用标准角数据经由纳克式装订修改元件的尺寸/位置/颜色。 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> 

下面的代码:

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); 
     }) 
     } 
    } 
    }  
}); 
+0

从来没有想过如何将ng样式与函数结合使用,并以这种方式“传递”参数。很好的解决方案。谢谢! – ilmgb