2013-01-23 54 views
43

我知道如何在AngularJS一个视图条件,即会显示或隐藏DOM元素取决于条件:请与AngularJS渲染条件

<div ng-show="{{isTrue}}">Some content</div> 

但我如何创建一个渲染决定是否渲染div的条件?

回答

63

更新angularjs 1.1.5及以上的用户(在1.0.7不支持):

相关承诺: https://github.com/angular/angular.js/commit/2f96fbd17577685bc013a4f7ced06664af253944

角现在有一个条件渲染指令:ngIf

用法:

<div ng-if="conditional_expression"></div> 

注意,当一个元件被使用ngIf其范围被破坏,并且当元件被恢复

Documentation: directive-ngIf

创建一个新的范围除去对于老用户:

ngShow指令有条件地隐藏/显示元素。这将在其中一个新的稳定版本中进行更改,现在可在unstable版本中获得,与1.1.5一样。

如果要有条件地在DOM上添加/删除项目,请使用ngSwitch

<div ng-switch="showMe"> 
    <div ng-switch-when="true">Hello!</div> 
</div> 

实际上,这个指令是为处理超过1的案例而创建的,但是你也可以这样使用它。请参阅this回答关于更复杂的用法的例子。

+0

如果'ng-if'为false,DOM呈现负载但可能无法呈现? –

1

有这样做的至少两种方法:

  • 使用模板与条件呈现功能
  • 使用简单表达导致某些部分(参见this fiddle和下面的描述)

对于简单的组件,我建议坚持渲染功能。很容易理解。

$scope.render = function(condition) {   
    return condition ? "This is rendered when condition == TRUE" : "This is rendered when condition == FALSE"; 
}; 

,只是它包括在你的HTML,像这样:

{{render(true)}} 

您也可以用角指令包这件事,这将给你非常好的标记和无限的可能性!

+0

这是一个不错的方法。但我真的很期待像ng-render =“{{condition}}”这样的优雅,使它变得简单和容易 – Alon

+0

请仔细阅读我的答案 - 你可以用指令包装它,它会准确地给你你需要的东西 - 一个干净的标记,就像这样:''conditional-renderer condition =“someValue == true”> ...' 我不认为Angular提供了这个开箱即用的功能。 –

+2

创建渲染指令并不那么简单。 OP意味着他想改变dom结构,并且指令需要观察条件属性并销毁范围并释放相关的源,否则您可能会泄漏到内存中。 –

3

推荐的方法是使用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> 
+9

它在哪里推荐?在我看来,这对于小型html片段来说是一种矫枉过正。顺便说一句,你的小提琴不起作用。 – Alberto

0

angular-uiif指令。我相信这会很好地为你服务。

+0

看起来这是从Angular UI中删除的。不知道为什么。 –

+1

@bmoeskau可能是因为它现在是AngularJS的一部分,自v1.1.5开始 – rdjs

+0

因为AngularJS核心正在迎头赶上。 – demisx