【发布时间】:2013-09-11 14:26:46
【问题描述】:
我正在尝试创建一组 AngularJS 指令,它们将有条件地呈现块或内联页面内容的互斥段。例如,我设想了一种只呈现第 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 元素。
作为对这个概念的首次尝试,我将内置的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 的元素方面并没有取得多大成功。我怀疑我需要更好地了解嵌入的工作原理,但似乎没有太多文档。
所以,如果您能建议使用正确的技术,或者为我指明一些相关教程的方向,我将不胜感激。
谢谢, 蒂姆
【问题讨论】:
-
你看过ngSwitch吗?它是为此目的而制作的。
-
@OverZealous:是的,你说得对,ngSwitch 是一个很好的模型。然而,虽然它同时支持元素和属性模式,但元素模式在页面中留下了一个
元素,这不是有效的 HTML,是我试图克服的具体问题。
标签: angularjs angularjs-directive transclusion