2014-02-27 89 views
2

我可以寫ng-repeat來迭代Django模型字段中的選項並顯示它們嗎?我該怎麼做?我應該爲這個還是什麼做一個單獨的API?從django模型中選擇選項

APPROVAL_CHOICES = (
     (u'Good condition', u'Good condition'), 
     (u'Bad condition', u'Bad condition'), 
     (u'Broken', u'Broken'), 
    ) 
status = models.CharField(max_length=20, choices=APPROVAL_CHOICES) 

我有類似於下面的東西,但它不工作:

<label>Statuss</label> 
    <select> 
     <option value="" selected>--Please select Inventory statuss--</option> 
     <option value="inventory.status[0]" >Good Condition</option> 
     <option value="inventory.status[1]" >Bad Condition</option>  
     <option value="inventory.status[2]" >Broken</option> 
    </select><br/> 

這裏是我的API:

objects: [ 
    { 
     category: {}, 
     count: 1, 
     created: "2014-02-24T16:07:12.903555", 
     description: "Car description for image", 
     id: 1, 
     location: "IT nodala", 
     name: "Baterija AA", 
     resource_uri: "/api/v1/inventory/1", 
     slug: "baterija-aa", 
     status: "Good condition" 
    }, 
+0

呃..什麼是不準確的工作?你是否已經嘗試使用_display()方法來顯示所選字段的可讀文本值? –

+0

我無法在使用angularjs前端顯示選項。沒有嘗試過,你能舉個例子嗎? – user3305175

+0

想象一下,我對angular.js一無所知,但我對django有所瞭解。 django意味着什麼你想做什麼?如果你想打印出某個字段的顯示值,則使用get_foo_display方法。如果你想跳過用於渲染的Django表單,並且只需將序列化的表單域和選項從django推送到html,那麼你將不得不寫一些東西來替換帶有序列化的表單域渲染。 –

回答

0

使用NG重複這樣

'<select data-ng-model="selectedField">' + 
     ' <option data-ng-repeat="v in choices" value="v">v</option>' + 
'</select> ' ; 
+0

它顯示值,但它在提交表單後不會選擇當前值。有小費嗎? – user3305175

+0

檢查選擇的ngModel ...如果「v在選擇」您的「v」是一個對象,而不是文本字段,那麼你可能需要這樣的東西:'選項data-ng-repeat = 「object.valuefield」> object.textfield' – harishr

+0

不是它甚至不顯示任何東西,我不知道發生了什麼,但我有這個''但是什麼也沒有顯示出來 – user3305175

0

我想你的問題是關於如何使用select帶有角度js的標籤,您可以使用ngOption directive。 從AngularJS docs

ngOptions

的ngOptions屬性可以被用於動態地生成用於使用通過評估ngOptions comprehension_expression得到的數組或對象的元素的元素的列表。

當選擇菜單中的項目時,由選定選項表示的數組元素或對象屬性將綁定到由ngModel指令標識的模型。

...注意:當您希望將選擇模型綁定到非字符串值時,ngOptions爲應該使用的元素提供了一個迭代器功能,而不是ngRepeat。這是因爲選項元素目前只能綁定到字符串值。

與此jsfiddles

<body ng-app="demoApp"> 
    <div ng-controller="DemoController"> 
    <div> 
     <h2>Incorrect</h2> 
     <p> 
     We might expect the select box to be initialized to "two," 
     but it isn't because these are two different objects. 
     </p> 
     <select 
     ng-model="incorrectlySelected" 
     ng-options="opt as opt.label for opt in options" 
     > 
     </select> 
     The value selected is {{ incorrectlySelected.value }}. 
    </div> 
    <div> 
     <h2>Correct</h2> 
     <p> 
     Here we are referencing the same object in <code>$scope.correctlySelected</code> 
     as in <code>$scope.options</code>, so the select box is initialized correctly. 
     </p> 
     <select 
     ng-model="correctlySelected" 
     ng-options="opt as opt.label for opt in options" 
     > 
     </select> 
     The value selected is {{ correctlySelected.value }}. 
    </div> 
    </div> 
</body> 

檢查docs form more exmaples