在Angular Directive中的replaceWith之后观察svg元素

时间:2014-04-24 10:31:25

标签: angularjs svg angularjs-directive snap.svg

最近一直试图建立一种用于插入内联svgs的防弹指令。它工作得很好,但最近我想添加一些动画,当类“animate”添加到插入的元素时触发。问题是$watch适用于旧元素(replaceWith之前的元素)。

我一直在尝试任何事情,但我不能让它发挥作用。如何在替换后访问该元素?

这是我的代码:

angular.module('test')
.directive('svgPng', ['$compile', function ($compile) {
  return {
    link: function(scope,elem,attrs) {
      elem.on('load', function(){
        var ext = function(s){return s.substr(s.length-3);},
          src = attrs.src;
        if (ext(src) === 'svg'){
          if(window.Modernizr && window.Modernizr.svg){
            Snap.load(src, function (svg){
              elem = elem.replaceWith($compile(svg.node)(scope));
              if(attrs.animate === 'true'){
                scope.$watch(function() {return elem.attr('class'); }, function(newValue){
                 //some animation
                }
              }
              console.log(elem); //gives old elem instead of svg.node
            });
          } else {
            if(attrs.fallback){
              elem.attr('src', attrs.fallback);
            } else {
              elem.attr('src', attrs.src.substr(3) + 'png');
            }
          }
        }
      });
    }
  };
}]);

1 个答案:

答案 0 :(得分:2)

elem没有使用新编译的元素进行更新,因为.replaceWith不返回新元素。 http://api.jquery.com/replacewith/

  

与大多数jQuery方法一样,.replaceWith()方法返回jQuery对象,以便可以将其他方法链接到它上面。但是,必须注意返回原始jQuery对象。此对象引用已从DOM中删除的元素,而不是已替换它的新元素

您需要存储已编译的元素并替换为该元素。

var compiled = $compile(svg.node)(scope);
elem.replaceWith(compiled);
elem = compiled;
相关问题