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.

Alex
  • 159
  • 14

2 Answers2

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;
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • 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. – Alex Aug 21 '15 at 16:45
  • can you provide a fiddle ? – Anik Islam Abhi Aug 21 '15 at 16:56
  • 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!! – Alex Aug 21 '15 at 17:16
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>
Community
  • 1
  • 1
Ken Bellows
  • 6,711
  • 13
  • 50
  • 78