0

I need to populate select(option) element inside template html file from controller. I could do it successfully, but can't give default value(to avoid the first empty option)

template.html file

...
<select name="drill_down" id="drill_down" ng-model="drill_down"
ng-options="item.value for item in items"></select>
...

controller.js file

(function () {
    'use strict';

var app = angular.module('appname', []);

app.config(function($stateProvider) {
    $stateProvider
        .state('appname', {
            url: '/appname',
            templateUrl: '/appname/template.html',
            controller: 'AppCtrl'
        });
});

app.controller('AppCtrl', AppCtrl);

function AppCtrl($scope, MyService) {
    $scope.college_majors_full = [];
    $scope.job_title_functions = [];

    MyService.getData().then(function(rows) {
        $scope.items = rows;   // this works - populates select options

        $scope.drill_down = $scope.items[0].value;  // this doesn't work
    });
...

Any help? Thanks.

2 Answers 2

1

Your options has only text property of your items

You are assigning value instead of id

Try like this

$scope.drill_down = $scope.items[0].value; 

Or you can create value text type in option

Try like this

View

<select name="drill_down" id="drill_down" ng-model="drill_down"
ng-options="item.id as item.value for item in items"></select>

Controller

$scope.drill_down = $scope.items[0].id;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help! It works. But now it selects the last option as default. Even I select another option, only the last option is selected always.
can you provide a fiddle ?
I solved it myself. The issue was that I didn't write data structure correctly. JSON data structure: items = [{name:'xxx', value:'first'}, ...] But I used ... ng-options="item.id as item.value for item in items... I should write name instead of id Thanks!!
0

You should be able to set a default value via ngModel. See this answer about setting a default value for ngOption:

var app = angular.module('optionsApp', []);

app.controller('optionsCtrl', function($scope) {
  $scope.prop = {
    "type": "select",
    "name": "Service",
    "value": "Service 3",
    "values": ["Service 1", "Service 2", "Service 3", "Service 4"]
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="optionsApp">

  <div ng-controller="optionsCtrl">
    <select ng-model="prop.value" ng-options="v for v in prop.values"></select>
  </div>

</div>

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.