Mark 的回答会起作用,但是,该示例过于有限,无法显示整个画面。虽然 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两次 是多余的,对性能不利并且对您的牙齿也不利。你应该怎么做?只需在 应该 编译你的 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
现在,正如承诺的那样,这是您来这里的解决方案:
使用replace: 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: "="
}
};
});