【问题标题】:Watch svg element after replaceWith in Angular Directive在 Angular 指令中替换后观看 svg 元素
【发布时间】:2014-06-09 14:07:14
【问题描述】:

最近一直在尝试构建一种用于插入内联 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');
            }
          }
        }
      });
    }
  };
}]);

【问题讨论】:

    标签: angularjs svg angularjs-directive snap.svg


    【解决方案1】:

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

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

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

    var compiled = $compile(svg.node)(scope);
    elem.replaceWith(compiled);
    elem = compiled;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 2019-10-21
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      相关资源
      最近更新 更多