如何设定的一个选择使用创建纳克选项的初始值与一个对象作为angularjs值 [英] How to set the initial value of a select created using ng-options with an Object as the value in angularjs

查看:106
本文介绍了如何设定的一个选择使用创建纳克选项的初始值与一个对象作为angularjs值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须用于更新从RESTful服务填充记录的形式。

I have a form used to update a record populated from a restful service.

一个字段的使用选择了一个查找的价值,我将它绑定到一个对象在我的模型。

One of the fields uses a select for a look-up value and I'm binding it to an object in my model.

在选择正确创建和选择选项作出正确更改我的模型。

The select is created correctly and choosing options makes the correct changes to my model.

问题是,当我最初加载页面的选择是空白的。

The problem is when I initially load the page the select is blank.

有没有办法正确地设定初始值,而无需抓取的查询对象并匹配ID来获得自动生成的索引位置?

Is there a way to set the initial value correctly without having to crawl the look-up object and match the id to get the auto-generated index position?

或者更好的是,设置的值是对象,而不是一个自动生成的索引。

Or better yet, set the value to be the object instead of an auto-generated index.

<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"}];

}

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

推荐答案

这是因为你有你在这里工作的两个不同的对象。您有

This is because you have two different objects you're working with here. You have

    {
        "description": "Description of course 37.",
        "id": "37",
        "name": "Course 37 Name"
    }

定义了两次,创建了两个不同的引用。如果使用同一个对象,它会正常工作。请参见 http://jsfiddle.net/Jxydp/14/ (有可能做的更好的办法,但它说明我的观点)

defined twice, creating two different references. If you use the same object, it will work as expected. See http://jsfiddle.net/Jxydp/14/ (There's probably a better way of doing it, but it illustrates my point)

这篇关于如何设定的一个选择使用创建纳克选项的初始值与一个对象作为angularjs值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆