2014-01-11 26 views
5

我正在研究一個角度項目,我需要根據一系列問題創建一個表單。我想爲數組中的每個問題創建ng-model使用{{expression}}動態創建ng-model不起作用?

所以我想出了類似下面的東西,但它不工作。

<div class="form-group" data-ng-repeat="question in questions"> 
    <label for="{{question.label}}" class="col-md-2 control-label"> 
     {{question.label}}: 
    </label> 
    <div class="col-md-10"> 
     <input type="text" 
       class="form-control" 
       name="{{question.label}}" 
       data-ng-model={{question.label}} 
       required /> 
     <span class="error" 
       data-ng-show="formQuickView.{{question.label}}.$error.required"> 
      Required! 
     </span> 
    </div> 
</div>     

有人可以幫我解決這個問題嗎?
感謝提前堆。

回答

7
formQuickView[question.label].$error.required 

這是常規的JavaScript語法。您想使用由question.label定義的名稱訪問formQuickView的財產。

更新

不知怎的,我錯過了要點,該ng-model表達。基本上你在這裏做同樣的事情。你有兩個選擇(技術上只有一個):

  • 對象添加到你的範圍,說questions,然後用questions[question.label]
  • 當你有一個表單,然後給它一個名稱,並自動添加一個對象。例如。 <form name="questions" ....和上面一樣。
+0

感謝您的,但我的主要問題是NG-模型。我可以創建一個類似{{表達式}}的模型嗎? – loveNZ

+0

@loveNZ對不起,我更新了這個問題。 – zeroflagL

4

ng-model不適用於{{}}它認爲傳遞給它的字符串作爲引用scope屬性的表達式。

我不確定是否正確理解您的代碼。在你的代碼中,我認爲data-ng-model="question.label"應該工作。

如果您想引用在label字段中指定的動態字段。與你的NG-模型試試這個:

<input type="text" ng-model="question[question.label]"/> 

DEMO

+0

謝謝我得到它與這樣的ng-model =「question.value」一起工作,然後通過所有我的問題對象的value屬性保存它的循環來獲取值。 – loveNZ

+0

@loveNZ:關於'data-ng-model =「question.label」的聲明有效嗎? –