0

I have a select list created with ng-repeat and not ng-options. The issue I have is that there is an extra blank list item that disappears as soon as the user change the value.

The answer to AngularJS - extra blank option added using ng-repeat in select tag mentions that the selected item should be initialized to avoid that issue. I did it but I still have a blank entry.

HTML:

<select ng-model="selectedLanguage">
  <option ng-repeat="language in languages" value="{{language}}" ng-selected="selectedLanguage == language">{{language.name}}</option>
</select>
<h2>{{selectedLanguage}}</h2>

Controller:

app.controller('Ctrl', function($scope) {
  $scope.languages = [{ name: "English", key: 'en' }, { name: "French", key: 'fr'}];
  $scope.selectedLanguage = $scope.languages[0];
});

The Plunker

Community
  • 1
  • 1
Sydney
  • 11,964
  • 19
  • 90
  • 142

1 Answers1

2

You should use ng-options I updated your plunkr

http://plnkr.co/edit/Iz7wFfG9l6wmQ50w2RpP

HTML

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script data-require="angular.js@1.2.1" data-semver="1.2.1" src="http://code.angularjs.org/1.2.1/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <h1>Hello Plunker!</h1>
    <select ng-model="selectedLanguage" ng-options="language.name | uppercase for language in languages">
    </select>
    <h2>{{selectedLanguage}}</h2>
  </body>

</html>

JS (no changes)

// Code goes here

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

app.controller('Ctrl', function($scope) {
  $scope.languages = [{ name: "English", key: 'en' }, { name: "French", key: 'fr'}];
  $scope.selectedLanguage = $scope.languages[0];
});
shaunhusain
  • 19,630
  • 4
  • 38
  • 51
  • My `option` text is actually using a filter: ``, so I don't think I can do it with `ng-options`. Can I? – Sydney Mar 22 '14 at 20:14
  • 1
    Believe you can still use the filter in the ng-options http://stackoverflow.com/questions/16644402/angular-use-filter-on-ng-options-to-change-the-value-displayed I tried it seems to work http://plnkr.co/edit/Iz7wFfG9l6wmQ50w2RpP – shaunhusain Mar 22 '14 at 20:25
  • Great glad this worked out, I didn't know that about ng-options either but it's always a struggle for me when doing selects in angular so I try to keep it as simple as possible. – shaunhusain Mar 22 '14 at 20:46