2015-03-02 128 views
0

我試圖用一個三元運算符來建立我的模板的一部分:角三元運營商

account.accountType === "" ? "" : "Type: " + account.accountType

這段代碼應該離開了類型標籤,如果它是空的。然而,該類型的標籤總是存在:

結果爲true:Type:
計算爲false:Type: {{ account.accountType }}

我所期望的行爲是:

結果爲true:""
計算爲false: Type: {{ account.accountType }}

這是三角形運算符的缺點,還是我的代碼中有錯誤?謝謝!

回答

2

""null不一樣。

我建議你使用null"",等的是 「falsy」 和行爲執行以下操作:

account.accountType ? "Type: " + account.accountType : "" 

甚至(感謝gustavohenke):

account.accountType && "Type: " + account.accountType 

如果你想有條件地在你的視圖中包含HTML,你可能最好使用類似ng-if的東西:

<span ng-if="account.accountType" class=".....">Type: {{ account.accountType }}</span> 
+1

可能更短:'account.accountType &&「類型:」+ account.accountType' – gustavohenke 2015-03-02 19:57:43

+0

@gustavohenke真。謝謝。 – JLRishe 2015-03-02 20:00:41

+0

這個伎倆。謝謝! – mattchue 2015-03-02 20:08:34