2013-10-26 94 views
3

我想在SVG元素上使用Angular 1.2.0rc3動畫ngRepeat,但是我找不到我的代碼無法工作的原因。在SVG元素上的角度動畫

其實,下面的代碼工作完美:

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100"> 
    <rect ng-repeat="item in itemsList" width="10" height="50" fill="gold" data-ng-attr-x="{{$index*15}}" class="animation" /> 
</svg> 

<div> 
    <div ng-repeat="item in itemsList" class="animation">[{{$index}}] {{item}}</div> 
</div> 
.animation.ng-enter, 
.animation.ng-leave 
{ 
    transition-property: opacity; 
    transition-duration: 2000ms; 
} 

.animation.ng-enter.ng-enter-active, 
.animation.ng-leave 
{ 
    opacity: 1; 
} 

.animation.ng-enter, 
.animation.ng-leave.ng-leave-active 
{ 
    opacity: 0; 
} 

Fiddle

但對於某些神祕的原因,當我把這些線在我真正的項目,則<rect>元素不再生氣了。然而,<div>元素仍然是動畫。最後,當我手動添加現有元素上的.ng-leave.ng-leave-active類(例如使用Firebug)時,我可以看到<rect>逐漸消失,如預期的那樣。一個相當不錯的Heisenbug,對吧?

請注意,我也在我的項目中使用jQuery

有人已經遇到過類似的問題,或者只是對發生了什麼有所瞭解?

回答

9

在我的項目AngularJS和jQuery的源代碼中挖了很長時間之後,看起來問題來自jQuery。事實上,我的例子工程without jQuery,但打破with it

讓我們來深入:Angular需要動態添加類到元素中以便爲它們設置動畫。爲此,它使用addClass()方法(see the call in the code)。 addClass()jqLite version很簡單,可以在現代瀏覽器中使用SVG元素。 在jQuery的中,情況並非如此,如this question所示。

解決方法是,不使用jQuery可言,用jQuery SVG和他的DOM擴展,糾正問題......

<script src="jquery.js"></script> 
<script src="jquery.svg.js"></script> 
<script src="jquery.svgdom.js"></script> 
<script src="angular.js"></script> 
<script src="angular-animate.js"></script> 

...或者乾脆使用的addClass()的jqLit​​e版本:

(function($) { 
    'use strict'; 

    $.fn.addClass = function (cssClasses) 
    { 
     this.each(function() 
     { 
      var element = this; 
      if (cssClasses && element.setAttribute) { 
       var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') 
             .replace(/[\n\t]/g, " "); 

       $.each(cssClasses.split(' '), function(i, cssClass) { 
        cssClass = cssClass.trim(); 
        if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { 
        existingClasses += cssClass + ' '; 
        } 
       }); 

       element.setAttribute('class', existingClasses.trim()); 
      } 
     }); 

     return this; 
    }; 
})(jQuery); 
+0

很好調查!希望你能在未來用別的方式挽救別人的頭痛。 –