如何设置使用ng-options创建的选择的初始值,其中Object为angularjs中的值

Div*_*ver 1 angularjs

我有一个表单用于更新从restful服务填充的记录.

其中一个字段使用select作为查找值,我将它绑定到模型中的对象.

正确创建选择并选择选项可以对我的模型进行正确的更改.

问题是当我最初加载页面时,select是空白的.

有没有办法正确设置初始值,而不必抓取查找对象并匹配id以获取自动生成的索引位置?

或者更好的是,将值设置为对象而不是自动生成的索引.

<div ng-controller="MyCtrl">
    Id: <input ng-model="course.id" readonly><br>
    Cost: <input ng-model="course.cost" ng-required="true"><br>
    Title: <select ng-model="course.courseTitle" ng-options="title.name for title in courseTitles">
      </select> {{course.courseTitle.description}}<br>
    Length: <input ng-model="course.length" ng-required="true"><br>
    <br>
    Id: {{course.id}}<br>
    Cost: {{course.cost}}<br>
    Title: {{course.courseTitle.name}}<br>
    Length: {{course.length}}
</div>

function MyCtrl($scope) {
    $scope.course = {
        "id": "108",
        "cost": "155",
        "courseTitle": {
            "description": "Description of course 37.",
            "id": "37",
            "name": "Course 37 Name"
        },
        "length": "7"
    };

    $scope.courseTitles = [{
        "description": "Description of course 37.",
        "id": "37",
        "name": "Course 37 Name"},
    {
        "description": "Description of course 63.",
        "id": "67",
        "name": "Course 63 Name"},
    {
        "description": "Description of course 88.",
        "id": "88",
        "name": "Course 88 Name"}];

}
Run Code Online (Sandbox Code Playgroud)

我在这里创造了一个小提琴 - http://jsfiddle.net/bcarter/Jxydp/

Mar*_*hes 5

使用ng-options的"track by"子句

<select ng-model="course.courseTitle" 
        ng-options="title.name for title in courseTitles track by title.id">
</select>
Run Code Online (Sandbox Code Playgroud)

这将导致比较通过title.id == other.id而不是title == other进行检查