简体   繁体   中英

Blank option with empty string created in select using AngularJS

I've created an angularJS select box which will filter the results in a table based on the selected value in the select box.

Now, the select box is created using an object 'user['location']' which has locations as keys. Also, I'm grabbing the default user location '${city}' as soon as the page is loaded, passing it on to my select box, and filter the results accordingly in the table.

If the user's current location doesn't match any of the options in my select box, then no filter should be applied!

For eg, if the user location is 'London', since there's nothing like in 'London' in my object, it should select the first option - 'Select City'.

But currently it is creating an empty string like <option value= "? string:London ?"></option> above that and is selecting it!

How, do fix it?

Here's my code:

HTML:

<select class="form-control" ng-model="user.loc" ng-init="user.loc = '${city}'">
  <option value="" ng-selected="!checkKey(user.loc)">Select City</option>            
  <option value="{{key}}" ng-selected="key == user.loc" ng-repeat="(key, value) in user['location']">{{key}}</option> 
</select>

JS:

$scope.user['location'] = {Sydney: 5, Hong Kong : 7, NYC : 3, Toronto: 1};

$scope.checkKey = function(loc) {
  if(loc in $scope.user['location']){
    return true;
  } else {
    return false;
  }            
};

I think I understand what you are trying to do here. But instead of checking the values using checkKey , you can do it once when your controller is loaded.

Also, you can leverage ngOptions to render available options in the select box.

 angular.module('myapp', []) .controller('myctrl', function($scope) { $scope.user = {}; $scope.user['location'] = { 'Sydney': 5, 'Hong Kong': 7, 'NYC': 3, 'Toronto': 1 }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myapp" ng-controller="myctrl"> <select class="form-control" ng-model="user.loc" ng-init="user.loc = user.location['London']" ng-options="value as key for (key, value) in user.location"> <option value="">Select City</option> </select> </div> 

You can change ng-init with your own value, as you were doing, and it should work fine with it.

Ok, I tried this and it worked!

<select class="form-control" ng-model="user.loc">
  <option value="" ng-selected="!checkKey(user.loc)">Select City</option>            
  <option value="{{key}}" ng-selected="key == '${city}'" ng-repeat="(key, value) in user['location']">{{key}}</option> 
</select>

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