2014-02-27 71 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