2013-01-23 168 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