如何阻止angular在自定义指令中将属性传递给被替换的元素
How to stop angular from passing attributes to replaced element in custom directive
我有一个自定义的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: '@'
}
};
})
相关文章:
- jQuery appendTo 替换元素而不是添加元素,如果正在添加的元素预先存在于列表中
- 如何用一些已编译的HTML替换元素的值
- 如何替换元素属性中的部分文本
- 替换
元素中的特殊字符的问题
- 为什么这个脚本只工作一次?只替换元素一次,然后再也不替换
- JS如何在加载页面之前替换元素(awesomium c#)
- Javascript.替换元素“<termref/>"用规则的“;文本”;
- 替换元素中字符串的所有位置
- regex替换元素文本
- 在Javascript中,如何用变量替换元素的名称
- 如何实现 Angular 指令来替换元素,但仅限于某些情况
- 事件调用在 ajax 替换元素后多次
- 替换元素后,无法单击该元素
- jQuery查找并替换元素中的关键字
- 如何在 JavaScript 中用 DOM 操作函数替换元素内容
- .each(从html元素生成下拉列表,替换元素)
- 替换元素中的类名,但不删除此元素中的其他类纯javascript
- Javascript push()替换元素,而不是追加
- 如何替换元素标记,然后将其添加到现有元素
- 查找并替换元素's类使用jQuery