AngularJS:如何转移和替换包含的元素
我试图创建一组AngularJS指令,有条件地呈现块或内联页面内容的互斥段。例如,我设想了一种只渲染第n个子元素的机制:AngularJS:如何转移和替换包含的元素,angularjs,angularjs-directive,transclusion,Angularjs,Angularjs Directive,Transclusion,我试图创建一组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> <d
<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>
要实现这一点,只需将restrict
修改为E
,并将监视属性的名称更改为条件
。以下是我对内置实现的修改版本:
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
,您看过了吗?它就是为了这个目的而制造的。@Over热心:是的,你说的对,ngSwitch是一个很好的模型。然而,尽管它同时支持元素和属性模式,元素模式在页面中留下了一个元素,这不是有效的HTML,这是我试图克服的特定问题。不幸的是,“替换”选项似乎只有在定义模板时才起作用,在这种情况下,原始元素将替换为渲染模板。在上面的示例中,设置replace:true无效。这可能仍然是解决方案的一部分,但我认为通过“compile”或“link”函数操作或填充该模板需要额外的步骤。您为什么要添加关于使用元素的内容,您知道您可以使用注释吗?对于我需要创建的一些指令,包含元素还将包含嵌套的指令元素(如ngSwitch),我们希望在所有指令中创建一致的语法。
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'E',
replace: true, // ** //