AngularJS和Select

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AngularJS和Select相关的知识,希望对你有一定的参考价值。

我无法理解为什么我的Angular <select>没有将默认值添加到我想要的类别。

我有一个从Parse数据库返回的对象;对象是这样的(这是“选中”选项):

$scope.item.category = { id: 'uosDHIF', className: 'Category', name: 'Projects' }

我也有一个类别列表:

$scope.categories = [{ id: 'uosDHIF', className: 'Category', name: 'Games' }, { id: 'uosDHIF', className: 'Category', name: 'Random' }, { id: 'uosDHIF', className: 'Category', name: 'Projects' }]

在我的html中我得到的是这样的选择:

<select name="category" class="form-control mb-10" ng-model="item.category" ng-options="category.name for category in categories"></select>

我可以选择一个新的类别并将其分配给该项目,然后我可以使用item.save()保存该项目,但我无法做的是选择的(ng-model)似乎不起作用,当我第一次进入页面我总是得到默认的空白选项,即使我在登录控制台时有类别。

此外,我能够使用我自己创建的一个简单对象,但是这个对象是从Parse中的数据库返回的,所以我不确定这是不是问题,或者我只是错过了那里的东西。

谢谢您的帮助。

注意:我已经阅读了与我类似的其他StackOverflow问题,但它们对我没有帮助。

答案

实际上,在ng-options上,您必须指定模型的值(category as category.name =>您为ng-model选择类别,但按名称显示)。

匹配通过引用进行,因​​此您需要相同的对象(类别:$ scope.categories [0])。

你可以试试:

JS

$scope.categories = [
    { id: 'uosDHIF', className: 'Category', name: 'Games' }, 
    { id: 'uosDHIF', className: 'Category', name: 'Random' }, 
    { id: 'uosDHIF', className: 'Category', name: 'Projects' }
];

$scope.item = { 
    category : $scope.categories[0]
};

HTML

<select name="category" class="form-control mb-10" ng-model="item.category" ng-options="category as category.name for category in categories"></select>
另一答案

请更改html如下..希望这是有帮助的。

ng-model="item.category.id" ng-options="category.id as category.name for category in categories">

以上是关于AngularJS和Select的主要内容,如果未能解决你的问题,请参考以下文章

AngularJS ——ngResourceRESTful APIs 使用

使用 AngularJS,如何在视图和控制器同步特定更改后触发代码执行?

AngularJS

angularjs中select下拉选择第一个选项为空白的解决办法

从 AngularJS url 中删除片段标识符(# 符号)

初入AngularJS基础门