2

I'm using an HTML select with the following data and scope code (below). I cannot get the initial value to select in the Select list from the scope data. Can someone point out what I'm messing up?

   $scope.hourOptions = [
            { value:'0',  key: '12AM'},
            { value:'3600',  key: '1AM'},
            { value:'7200',  key: '2AM'},
            { value:'10800',  key: '3AM'},
            { value:'14400',  key: '4AM'},
            { value:'18000',  key: '5AM'},
            { value:'21600',  key: '6AM'},
            { value:'25200',  key: '7AM'},
            { value:'28800',  key: '8AM'},
            { value:'32400',  key: '9AM'},
            { value:'36000', key: '10AM'},
            { value:'39600', key: '11AM'},
            { value:'43200', key: '12AM'},
            { value:'46800', key: '1PM'},
            { value:'50400', key: '2PM'},
            { value:'54000', key: '3PM'},
            { value:'57600', key: '4PM'},
            { value:'61200', key: '5PM'},
            { value:'64800', key: '6PM'},
            { value:'68400', key: '7PM'},
            { value:'72000', key: '8PM'},
            { value:'75600', key: '9PM'},
            { value:'79200', key: '10PM'},
            { value:'82800', key: '11PM'}
        ];

Here's the view

<select id="timeOfDay" class="form-control"
        data-ng-options="option.value as option.key for option in hourOptions"
        data-ng-model="topic.timeOfDay"
        required
        ></select>

The $scope.topic value is set to 72000 as such:

$scope.topic.timeOfDay = 72000;

I've tried changing this to a string in the data-ng-init with no avail. Regardless what I do I cannot get the initial value to select itself in the select list. Any ideas?

1 Answer 1

5

Since option.value is string representation of numeric value you must provide ng-model value as string as well. And initialize it in the controller instead of using ng-init for initializing (though it wont cause an issue, but just that usage of it to initialize like this is not a good pattern)

Try:

$scope.timeOfDay = '72000';

and probably you meant to set ng-model as data-ng-model="timeOfDay" or viceversa.

Plnkr

Sign up to request clarification or add additional context in comments.

2 Comments

This was the problem. For some reason, the ng-init didn't do anything (though I assumed it would). Setting it to a string in the controller did the trick. I updated my code sample to be correct (had a typo with the scope setting). Thanks!
@DonnFelker You are welcome. ng-init expression is not watched and you do not use $scope explicity in ng-init, scope is implicit there. However it is not a good thing to initialize in ng-init as the ofiicial doc says.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.