0

最近一直在尝试构建一种用于插入内联 svg 的防弹指令。它工作得很好,但最近我想添加一些当类“动画”添加到插入元素时触发的动画。问题是$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');
            }
          }
        }
      });
    }
  };
}]);
4

1 回答 1

2

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

.replaceWith() 方法,像大多数 jQuery 方法一样,返回 jQuery 对象,以便其他方法可以链接到它。但是,必须注意返回的是原始的 jQuery 对象。这个对象指的是已经从 DOM 中移除的元素,而不是替换它的新元素

您需要存储已编译的元素并用它替换。

var compiled = $compile(svg.node)(scope);
elem.replaceWith(compiled);
elem = compiled;
于 2014-04-24T20:52:49.310 回答