How to select option in select list?

379 views Asked by At

I have option element in select:

$scope.countries = {0 : 'Select country...'};

And ng-model="selected" is integer 0;

But option is not selected. How I can select option with 0?

2

There are 2 answers

0
shreyansh On

If I got you correctly then you are looking for something like this

<html>
<body ng-app="myApp" ng-controller="HomeCtrl">

    <select ng-model="selected" ng-options="v for (k,v) in country ">
    </select>

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script>

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

    app.controller('HomeCtrl', ['$scope',  function($scope) {

        $scope.selected='Select country...';  // dafault to be displayed

        $scope.country={0 : 'Select country...', 1:'France', 2:'India', 3:'USA'};

    }]);

  </script>
</body>
</html>

Note :- The key of an object will always have to be of string data type. You cannot use integer or number , that will be treated as string only.

2
Jony-Y On

Im not sure I understood what you were trying to do... but I think you want to show the text when the value 0 is selected in the ngModel... so you want the ngOptions to go by the value but show the text?

so you want something like:

ng-options="country as country.id for country in countries track by country.id" please check.... so you can actually do something like

<select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">


    $scope.values = [{
  id: 1,
  label: 'aLabel',
  subItem: { name: 'aSubItem' }
}, {
  id: 2,
  label: 'bLabel',
  subItem: { name: 'bSubItem' }
}];

$scope.selected = { name: 'aSubItem' };

please check ngOptions docs