2017-04-01 88 views
0

我可以無縫地更改元素的屬性是這樣的:如何動態更改元素?

<input 
    name="{{ currentField.name }}" 
    type="{{ currentField.properties.type }}" 
    ... /> 

There is no problem.

但是,我需要動態改變元素(輸入,文本區域,選擇等)。

如果我嘗試更改元素,AngularJS不會渲染元素。相反,顯示HTML:

<{{ currentField.element }} 
    name="{{ currentField.name }}" 
    type="{{ currentField.properties.type }}" 
    ... /> 

Doesn't rendering the element.

這是例如{{currentField}}數據:

{ 
    element: 'textarea', 
    name: 'address', 
    properties: { 
     type: 'text', 
    } 
} 

問題出在哪裏?

回答

1

這樣使用它:

<textarea ng-if="currentField.element == 'textarea'" 
     name="{{ currentField.name }}" 
     type="{{ currentField.properties.type }}" 
     ... /> 

<input ng-if="currentField.element == 'input'" 
    name="{{ currentField.name }}" 
    type="{{ currentField.properties.type }}" 
    ... /> 
+0

有很多的元素。我是否應該爲每個代碼一次又一次地寫這些代碼? –

+0

如果有很多,那麼你可以創建一個指令。這裏是[類似的問題](http://stackoverflow.com/questions/24920456/creating-a-directive-with-a-variable-element-type)和[這個演示](http://codepen.io/ scarl3tt/pen/rsbpH),希望它有幫助 – anoop