Search code examples
angularjsangular-ngmodel

Using an Object with ngModel Option Select


I'm building a date-time selector in Angular and am having a hard time figuring out how to use an object with ng-model. I have a hash of hours with a name value of 1-12, each of which has an AM and PM value. I had no trouble getting ng-options to generate an option select with the right names/values, however I'm having a hard time figuring out how to get ng-model to select the correct one from the list based on the initial value I set in my newPost model.

I have the following markup in my view:

<div>
    <select name="hour" ng-options="hour.value as hour.name for hour in hours" ng-model="newPost.hour"></select>
</div>

Then in my controller I build my currentHour object like so:

var currentHourName = ((new Date()).getHours() + 24) % 12 || 12;
var currentHour = {
    name: currentHourName,
    value: {
        'AM': (((new Date()).getHours() + 24) % 12),
        'PM': (((new Date()).getHours() + 24) % 12) + 12
    }
};

// Ancillary attributes omitted for brevity.
$scope.newPost = {
    hour: currentHour
};


$scope.hours = [
    {name: 1, value: {'AM': 0,'PM': 12}},
    {name: 2, value: {'AM': 1,'PM': 13}},
    {name: 3, value: {'AM': 2,'PM': 14}},
    {name: 4, value: {'AM': 3,'PM': 15}},
    {name: 5, value: {'AM': 4,'PM': 16}},
    {name: 6, value: {'AM': 5,'PM': 17}},
    {name: 7, value: {'AM': 6,'PM': 18}},
    {name: 8, value: {'AM': 7,'PM': 19}},
    {name: 9, value: {'AM': 8,'PM': 20}},
    {name: 10, value: {'AM': 9,'PM': 21}},
    {name: 11, value: {'AM': 10,'PM': 22}},
    {name: 12, value: {'AM': 11,'PM': 23}}
];

What I'd like to know is how I can make this work with ng-model.


Solution

  • You can use the track by inside the ng-options. Except this angular does not know how to compare the equality between your ng-model and options. But if you provide the track by field name, it'll use this field to check equality.

    Here is a working example in plunker: Plunker Link