我正在尝试创建一组 AngularJS 指令,它们将有条件地呈现 block 或内联页面内容的互斥段。例如,我设想了一种只呈现第 n 个子元素的机制:
<selector member="index">
<div>This div is visible when $scope.index equals 0</div>
<div>This div is visible when $scope.index equals 1</div>
<div>This div is visible when $scope.index equals 2</div>
</selector>
但是,我的设计要求使用自定义元素标记(而不是应用于 HTML 元素的属性)来实现指令,并且在渲染完成时从 DOM 中删除这些 HTML 无效元素。因此,在上面的示例中,单个匹配
div
元素将保留。作为这个概念原型(prototype)的第一次尝试,我转换了内置的
ngIf
指令使用以下基于元素的语法:<if condition="true">
<p>This is visible</p>
</if>
<if condition="false">
<p>This is not visible</p>
</if>
只需修改
restrict
即可使其正常工作。至E
并将被监视属性的名称更改为 condition
.这是我对内置实现的修改版本:application.directive("if", ['$animate', function ($animate) {
return {
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'E',
compile: function (element, attr, transclude) {
return function ($scope, $element, $attr) {
var childElement;
var childScope;
$scope.$watch($attr.condition, function (value) {
if (childElement) {
$animate.leave(childElement);
childElement = undefined;
}
if (childScope) {
childScope.$destroy();
childScope = undefined;
}
if (toBoolean(value)) {
childScope = $scope.$new();
transclude(childScope, function (clone) {
childElement = clone;
$animate.enter(clone, $element.parent(), $element);
});
}
});
};
}
};
}]);
但是,我在消除包含
if
的情况下并没有取得太大的成功。元素。我怀疑我需要更好地理解嵌入是如何工作的,但周围似乎没有太多文档。因此,如果您可以建议使用正确的技术,或者向我指出一些相关教程的方向,我将不胜感激。
谢谢,
蒂姆
最佳答案
不是替换你想要的吗?
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'E',
replace: true, // ** //
这将取代
if
与您的content
关于AngularJS:如何转换和替换包含元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675529/