Angular: Binding objects to <select>

Davy Jones picture Davy Jones · Jun 19, 2013 · Viewed 7.9k times · Source

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".

Answer

Narretz picture Narretz · Jun 19, 2013

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