nemo_87
nemo_87

Reputation: 4791

Set default value on dynamically filled drop down in AngularJs

Is there an easy way to select default value when drop down is populated with data that is dynamically generated?

I have drop down that is populated with values for hours (actually every 15 minutes: ...,09:15, 09:30, 9:45, 10:00, 10:15, ...)

What I want to do is to select by default on page loading value 12:00 (noon).

I know that there is a way to do this by giving index of value, but I wanted to explore is there some better way to do it maybe?

This is my drop down:

<div class="col-md-2" ng-class="{ 'has-error has-feedback': addNewTestSession.sessionStartTime.$touched && addNewTestSession.sessionStartTime.$invalid }">
    <label for="sessionStartTime">Session Start Time<span class="mandatory">*</span></label>
    <select id="sessionStartTime" name="sessionStartTime" class="form-control" 
        ng-model="newTestSessionCtrl.formData.sessionTime"
        ng-options="time for time in newTestSessionCtrl.viewData.sessionStarTimeIntervals"
        ng-required="true">
        <option value="" disabled selected>Select</option>
    </select>
    <span ng-show="addNewTestSession.sessionStartTime.$touched && addNewTestSession.sessionStartTime.$invalid" 
        class="fa fa-warning form-control-feedback"
        uib-popover="This field is required." 
        popover-trigger="'mouseenter'"
        popover-placement="auto right"
        popover-class="additional-info"></span>             
</div>

And this function will generate data for it:

sessionStarTimeIntervals: this.generateTimeIntervalArray(15)

generateTimeIntervalArray(minutes) {
    let retVal = [];
    let hour = 0;
    let minute = 0;
    let whileTest = true;

    function addZeroIfOneDigitvalue(value) {
        if ((value + "").length === 1) {
            value = "0" + value;
        }

        return value;
    }

    while (whileTest) {
        if (hour === 24) {
            break;
        }

        retVal.push(addZeroIfOneDigitvalue(hour) + ":" + addZeroIfOneDigitvalue(minute));

        minute += minutes;
        if (minute >= 60) {
            minute = minute - 60;
            hour++;
        }
    }

    return retVal;
}

What would be the best way and approach for selecting 12:00 on every page load?

Upvotes: 0

Views: 831

Answers (1)

F.Igor
F.Igor

Reputation: 4350

You can pre-select the value filling the model variable for your select input.

During the $scope setup or in some part of your code when newTestSessionCtrl.formData is filled:

newTestSessionCtrl.formData.sessionTime='12:00';

In the HTML for SELECT

ng-init="newTestSessionCtrl.formData.sessionTime='12:00'"
ng-model="newTestSessionCtrl.formData.sessionTime"

Upvotes: 2

Related Questions