AngularJS选择列表与所选项目不匹配

时间:2013-07-23 14:50:53

标签: javascript html rest angularjs

我的AngularJS应用程序中有一个全局控制器,它为我提供了一个包含Attendee对象的数组。我想要的是修改我的CourseRegistration模型,其中包含一个特定的与会者对象。在编辑窗口中,我希望获得所有可能的与会者的下拉菜单,而应该选择当前的与会者。

我的html中有以下代码:

        <select ng-model="courseRegistration.attendee" ng-options="attendeeSelectItem.name for attendeeSelectItem in attendeeSelectItems"></select>

如果我使用JSON.stringify打印出courseRegistration.attendee并对相应的选项执行相同的操作,则会打印出相同的对象(相同的ID,相同的名称等)。但如果我为两个相同的对象做了类似(courseRegistration.attendee == attendeeSelectItem)的事情,那么我就会变错。

所以我的问题是如何确保当前所选项目(存储在courseRegistration.attendee中)与我的列表中的相应对象(由选项使用)匹配?

提前多多感谢。

JSFiddle:http://jsfiddle.net/2ddCy/

电贺 马克

2 个答案:

答案 0 :(得分:0)

基本上当你使用一个对象数组来填充一个选择时,它会选择整个对象,而不仅仅是你在选择列表中看到的那个项目。

有关详细信息和示例代码,请参阅此问题:Problems when using ng-options and ng-switch together

答案 1 :(得分:0)

我假设您的控制器中有以下内容?

$scope.courseRegistration = {attendee: {id: 2, name: "A Person"}}

如果是这样,比较失败的原因是虽然对象可能具有与当前选择的属性相同的属性,但它指的是内存中的不同对象,因此不被归类为相等。

现在作为一个快速黑客你可以对它们进行字符串化然后进行比较,但正确的方法是按键设置当前值:

$scope.courseRegistration = {attendee: attendeeSelectItems[1]};

或者只是存储id / name并将ng-options条件设置为仅绑定到该值:

$scope.courseRegistration = {attendee: 1};

<select ng-model="courseRegistration.attendee" ng-options="attendeeSelectItem.id as attendeeSelectItem.name for attendeeSelectItem in attendeeSelectItems"></select>