Angular: Binding objects to <select>

放肆的年华 提交于 2019-12-22 09:11:07

问题


Firstly, I should say that I have only attacked Angular.js for 2 days now so I may be approaching this whole thing wrong.

My example "Person" object (or model if I understand) has two properties, Firstname and Title. I have two fields <select> for title and <input type="text" /> for name. The Firstname binding works fine and I am happy, but the title is confusing me.

I am binding an object array with Code and Desc which populates fine. But when I want to get (on submit) or set (on load) it does not work because the binding uses the entire title object.

http://jsfiddle.net/qm7E7/11/

(Click on Next to display the serialized object.)

HTML

<div ng-app ng-controller="PersonCtrl">
    <form name="myForm" ng-submit="submit()">
        Title: <select ng-model="Person.Title" ng-options="t.Desc for t in TitleList">
        <option style="display: none" value="">Please select</option>
    </select>
        <br/>
    Firstname: <input type="text" ng-model="Person.Firstname" />      
        <br/>
        <input type="submit" value="Next" />
        <br/>
        <div id="obj"></div>
    </form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">

JS

// Person controller
function PersonCtrl($scope) {
    $scope.TitleList = [{Code: 'MR', Desc: 'Mr'},
                       {Code: 'MRS', Desc: 'Mrs'}]

    $scope.Person = {
        Firstname: 'dave',
        Title: 'MR'
    };

    $scope.submit = function () {
        $("#obj").text(JSON.stringify($scope.Person));
    };
}

Am I misunderstanding the whole concept or what. I should also say that I don't want to use the whole MVC routing concept. Just the objects and "2 way binding".


回答1:


The select input is a very special puppy in angular.

Here's an updated fiddle:

http://jsfiddle.net/qm7E7/16/

You could provide the data as an object, where the keys are the codes and the values are the description:

$scope.TitleList = {
    'MR' : 'Mr',
    'MRS' : 'Mrs'
};

And in your html:

<select ng-model="Person.Title" ng-options="code as desc for (code, desc) in TitleList">

the syntax is a little tricky. You can read more about it in the angular docs, especially the comments. http://docs.angularjs.org/api/ng.directive:select




回答2:


You need to specify the value

<select ng-model="Person.Title" ng-options="t.Code as t.Desc for t in TitleList">

http://jsfiddle.net/qm7E7/19/



来源:https://stackoverflow.com/questions/17193957/angular-binding-objects-to-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!