我知道如何在AngularJS一个视图条件,即会显示或隐藏DOM元素取决于条件:请与AngularJS渲染条件
<div ng-show="{{isTrue}}">Some content</div>
但我如何创建一个渲染决定是否渲染div的条件?
我知道如何在AngularJS一个视图条件,即会显示或隐藏DOM元素取决于条件:请与AngularJS渲染条件
<div ng-show="{{isTrue}}">Some content</div>
但我如何创建一个渲染决定是否渲染div的条件?
更新angularjs 1.1.5及以上的用户(在1.0.7不支持):
相关承诺: https://github.com/angular/angular.js/commit/2f96fbd17577685bc013a4f7ced06664af253944
角现在有一个条件渲染指令:ngIf
。
用法:
<div ng-if="conditional_expression"></div>
注意,当一个元件被使用ngIf其范围被破坏,并且当元件被恢复
创建一个新的范围除去对于老用户:
ngShow
指令有条件地隐藏/显示元素。这将在其中一个新的稳定版本中进行更改,现在可在unstable
版本中获得,与1.1.5
一样。
如果要有条件地在DOM上添加/删除项目,请使用ngSwitch
。
<div ng-switch="showMe">
<div ng-switch-when="true">Hello!</div>
</div>
实际上,这个指令是为处理超过1的案例而创建的,但是你也可以这样使用它。请参阅this回答关于更复杂的用法的例子。
有这样做的至少两种方法:
对于简单的组件,我建议坚持渲染功能。很容易理解。
$scope.render = function(condition) {
return condition ? "This is rendered when condition == TRUE" : "This is rendered when condition == FALSE";
};
,只是它包括在你的HTML,像这样:
{{render(true)}}
您也可以用角指令包这件事,这将给你非常好的标记和无限的可能性!
这是一个不错的方法。但我真的很期待像ng-render =“{{condition}}”这样的优雅,使它变得简单和容易 – Alon
请仔细阅读我的答案 - 你可以用指令包装它,它会准确地给你你需要的东西 - 一个干净的标记,就像这样:''conditional-renderer condition =“someValue == true”> ...' 我不认为Angular提供了这个开箱即用的功能。 –
创建渲染指令并不那么简单。 OP意味着他想改变dom结构,并且指令需要观察条件属性并销毁范围并释放相关的源,否则您可能会泄漏到内存中。 –
推荐的方法是使用NG-包括
例子:http://jsfiddle.net/api/post/library/pure/
<div ng-app="">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url"></div>
</div>
<!-- template1.html -->
<script type="text/ng-template" id="template1.html">
Content of template1.html
</script>
<!-- template2.html -->
<script type="text/ng-template" id="template2.html">
Content of template2.html
</script>
</div>
它在哪里推荐?在我看来,这对于小型html片段来说是一种矫枉过正。顺便说一句,你的小提琴不起作用。 – Alberto
看angular-uiif
指令。我相信这会很好地为你服务。
如果'ng-if'为false,DOM呈现负载但可能无法呈现? –