Sunny
Sunny

Reputation: 932

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 e.g., 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;
  }            
};

Upvotes: 0

Views: 1906

Answers (2)

Sunny
Sunny

Reputation: 932

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>

Upvotes: 0

31piy
31piy

Reputation: 23869

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.

Upvotes: 1

Related Questions