1

I am having problem with setting default for my select list. Any help on this would be appreciated. I looked at the other similar posts but the solutions are not seem to be working in my case.

I populate $scope.series in the controller. and then the drop down seems to be populating as well but it is not setting the default value.

<select name="repeatSelect" id="repeatSelect"
                            ng-init="selectedItem = series[0].code"
                            ng-model="selectedItem"
                            ng-options="serie.name for serie in series track by serie.code"
                            ng-change="update()"></select>

here is the json:

[
    {
        "code": "code1",
        "name": "name 1",
    },
    {
        "code": "code2",
        "name": "name 2",
    }
]

Following is the controller

angular.module("myApp", [])
.controller('myController', function ($scope, dataService) {
    dataService.getSeries(function (response) {
        $scope.series = response.data;
        console.log(response.data);
    })});

Where dataService is the service to get json file from $http get.

2
  • This is considered bad practice to use ngInit this way. Just set the value in the controller. This might also fix your issue. Commented Dec 11, 2015 at 20:50
  • 1
    BTW, also don't initialize the selectedItem to series[0].code, but to series[0], since that's what the ng-model contains. Commented Dec 11, 2015 at 20:51

2 Answers 2

2

You had ng-init which tries to evaluate expression when there was no value in series, because the ajax for it doesn't return the value yet.

So you need to set the ng-model value in ajax success instead of ng-init

Markup

<select name="repeatSelect" id="repeatSelect"
   ng-model="selectedItem"
   ng-options="serie.name for serie in series"
   ng-change="update()">
</select>

Code

angular.module("myApp", [])
.controller('myController', function ($scope, dataService) {
    dataService.getSeries(function (response) {
        $scope.series = response.data;
        $scope.selectedItem = $scope.series[0].code; //setting ng-model after getting data
        console.log(response.data);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

seems like adding this code to controller did the trick and no need to have ng-init as well.:

$scope.selectedItem = { code: $scope.series[0].code, name: $scope.series.name };

Comments

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.