我正在创建一个<row>
AngularJS 指令需要用可包含任何 HTML 代码的动态模板替换自身(执行后 <row>
标签不得出现在 DOM 中)。
使用replace: true
时出现的问题是它不适用于表的 <tr>
标签并且模板是动态选择的。
所以我试图找到一种方法来替换链接函数中的元素,但没有成功。
使用 jQuery 的 .replaceWith()
休息ngRepeat
由于未知原因。
有什么提示吗?
这是fiddle
最佳答案
马克的答案是可行的,但是,这个例子太有限,无法展示整个情况。虽然 Mark 的指令可能确实足以满足常见且简单的 UI 组件的需求,但对于更复杂的操作,这种模式是需要避免的。下面我详细解释这背后的原因。事实上,Angular已经提供了一种更简单的方法来用模板替换指令元素。它可以在这个答案的底部找到。
以下是指令在幕后的样子:
.directive('row', function ($compile) {
return {
restrict: 'E',
scope: {
items: "="
},
// Whether you define it this way or not, this is the order of
// operation (execution) behind every AngularJS directive.
// When you use the more simple syntax, Angular actually generates this
// structure for you (this is done by the $compile service):
compile: function CompilingFunction($templateElement, $templateAttributes, transcludeFn) {
// The compile function hooks you up into the DOM before any scope is
// applied onto the template. It allows you to read attributes from
// the directive expression (i.e. tag name, attribute, class name or
// comment) and manipulate the DOM (and only the DOM) as you wish.
// When you let Angular generate this portion for you, it basically
// appends your template into the DOM, and then some ("some" includes
// the transclude operation, but that's out of the $scope of my answer ;) )
return function LinkingFunction($scope, $element, $attrs) {
// The link function is usually what we become familiar with when
// starting to learn how to use directives. It gets fired after
// the template has been compiled, providing you a space to
// manipulate the directive's scope as well as DOM elements.
var html ='<div ng-repeat="item in items">I should not be red</div>';
var e = $compile(html)($scope);
$element.replaceWith(e);
};
}
};
});
我们能从中得到什么?很明显,为相同的 DOM 布局手动调用 $compile
两次是多余的,对性能不利并且对你的 dentry 也不好。你应该做什么?只需在应该编译的地方编译 DOM:
.directive('row', function ($compile) {
return {
restrict: 'E',
template: '<div ng-repeat="item in items">I should not be red</div>',
scope: {
items: "="
},
compile: function CompilingFunction($templateElement, $templateAttributes) {
$templateElement.replaceWith(this.template);
return function LinkingFunction($scope, $element, $attrs) {
// play with the $scope here, if you need too.
};
}
};
});
<小时/>
如果您想进一步深入了解指令,我喜欢将其称为非官方 AngularJS Directive Reference
一旦你完成了这里的头部:https://github.com/angular/angular.js/wiki/Understanding-Directives
<小时/>现在,正如所 promise 的,这是您来这里的解决方案:
使用替换:true
:
.directive('row', function ($compile) {
return {
restrict: 'E',
template: '<div ng-repeat="item in items">I should not be red</div>',
replace: true,
scope: {
items: "="
}
};
});
关于jquery - 如何替换 AngularJS 指令链接函数中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17090964/