如何阻止angular在自定义指令中将属性传递给被替换的元素

How to stop angular from passing attributes to replaced element in custom directive

本文关键字:替换 元素 属性 angular 何阻止 自定义 指令      更新时间:2023-09-26

我有一个自定义的angular指令,使用replace: true。当我这样做时,我注意到自定义标签中的所有属性都被转移到指令模板中的顶级元素中。有办法阻止它这样做吗?

<custom someAttr="someVal"></custom>

替换后,代码看起来像这样…

<div class="custom" someAttr="someVal"></div>

我希望它只是…

<div class="custom"></div>

但仍然能够访问someAttr的值在我的作用域…

.directive('custom', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      someAttr: '@'
    },
    template: '<div class="custom">{{someAttr}}</div>'
  }
});

任何想法?

我认为这个问题的答案可能会有所帮助:

当replace=true时,如何防止angular指令中的重复属性

这是@user2943490的建议:

.directive('foo', function() {
  return {
    // ..
    compile: compile
    // ..
  };
  function compile(tElement, tAttrs) {
    // destination element you want to manipulate attrs on
    var destEl = tElement.find(...);
    angular.forEach(tAttrs, function (value, key) {
      manipulateAttr(tElement, destEl, key);
    })
    var postLinkFn = function(scope, element, attrs) {
      // your link function
      // ...
    }
    return postLinkFn;
  }
  function manipulateAttr(src, dest, attrName) {
    // do your manipulation
    // ...
  }
})

这是@Enzey的另一种方法:

.directive('foo', function() {
    return {
        restrict: 'E',
        replace: true,
        template: function(element, attrs) {
            var template = '<div bar="{{bar}}" baz="baz"></div>';
            template = angular.element(template);
            Object.keys(attrs.$attr).forEach(function(attr) {'
                // Remove all attributes on the element from the template before returning it.
                template.removeAttr(attrs.$attr[attr]);
            });
            return template;
        },
        scope: {
          bar: '@'
        }
    };
})