简体   繁体   中英

How to populate the options value in select dropdown

I am trying to solve a weird bug that is on select element. For some reason, there is always one black option on the top of the dropdown.

I have something like this in html.

this element is included in my test controller.

<select ng-model="vm.pickTest">
  <option ng-repeat="test in vm.tests"
          ng-selected="test.id === vm.pickTest.id">{{test.title}}</option>
</select>

inside test controller

   //init controller codes...
     vm.pickTest = {'id':'id1', 'title':'title1'}

     vm.tests = [
       {'id':'id1','title':'title 1'},
       {'id':'id2','title':'title 2'},
       {'id':'id3','title':'title 3'},
     ]

so when the page first loads, it will pre-select 'title 1 ' by default. For some reason, I can see a blank option in my dropdown like:

(blank)
title 1 <---pre-selected
title 2
title 3

I have tried using

<select ng-model="vm.pickTest">
  <option value="" style="display: none;">test</option>
  <option ng-repeat="test in vm.tests"
          ng-selected="test.id === vm.pickTest.id">{{test.title}}</option>
</select>

as other posts suggested but still no lucks. I also don't want to use ng-option because of other restrictions in my codes. Can anyone help me to solve this issue? It's really annoying. Thanks a lot!

Try using ng-options instead. Here's the documentation .

I fully agree with @aup and @Brad. It is best to use ng-options .

But if you do have a restrict on the use of ng-option , you can use the following trick.

Live example on jsfiddle .

 angular.module('ExampleApp', []) .controller('ExampleController', function() { var vm = this; vm.tests = [{ 'id': 'id1', 'title': 'title 1' }, { 'id': 'id2', 'title': 'title 2' }, { 'id': 'id3', 'title': 'title 3' }, ]; vm.pickTest = vm.tests[0]; }) .directive('convertToObject', function() { return { require: 'ngModel', scope:{ convertToObject:"=" }, link: function(scope, element, attrs, ngModel) { ngModel.$parsers.push(function(val) { for(var i=0;i<scope.convertToObject.length;i++) { if(scope.convertToObject[i].id===val) return scope.convertToObject[i]; } return null; }); ngModel.$formatters.push(function(val) { return val.id; }); } }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="ExampleApp"> <div ng-controller="ExampleController as vm"> <select ng-model="vm.pickTest" convert-to-object="vm.tests"> <option ng-repeat="test in vm.tests" value="{{test.id}}">{{test.title}}</option> </select> <pre>{{vm.pickTest|json}}</pre> </div> </div> 

More about $parsers and $formatters .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM