RushVan
RushVan

Reputation: 363

Why does this empty <option> in ng-options clear all selections?

I have a plunker here to demonstrate.

I am using a blank option tag in my ng-options select.

    <select ng-model="food.fruitOne"
        ng-options="fruit.id as fruit.name for fruit in fruits | filter: food.fruitTwo && {id: '!' + food.fruitTwo} | filter: food.fruitThree && {id: '!' + food.fruitThree}">
       <option value="">-</option>
    </select>

The select list is used 3 times for 3 different ng-models. Strangely, if you make a selection from any of the choices and then change that selection back to the blank option all 3 choices switch to the blank option and the selects all crap out.

Interesting. In this plunk which does not use the filters, the selects don't act that way. Clearly the filter is the culprit. Why?

Thanks!

Upvotes: 1

Views: 765

Answers (2)

Stepan Kasyanenko
Stepan Kasyanenko

Reputation: 3186

This is error in yours filter in ng-repeat.

See updated plunker

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.food = {
    fruitOne: "",
    fruitTwo: "",
    fruitThree: ""
  };
  $scope.fruits = [{
    id: 1,
    name: 'apple'
  }, {
    id: 2,
    name: 'banana'
  }, {
    id: 3,
    name: 'orange'
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="plunker" ng-controller="MainCtrl">
  <label>Choice 1</label>
  <select ng-model="food.fruitOne" ng-options="fruit.id as fruit.name for fruit in fruits | filter:food.fruitTwo!=''?{id: '!' + food.fruitTwo}:{} | filter:food.fruitThree!=''? {id: '!' + food.fruitThree}:{}">
    <option value=""></option>
  </select>
  <label>Choice 2</label>
  <select ng-model="food.fruitTwo" ng-options="fruit.id as fruit.name for fruit in fruits | filter: food.fruitOne!=''?{id: '!' + food.fruitOne}:{} | filter: food.fruitThree!=''?{id: '!' + food.fruitThree}:{}">
    <option value=""></option>
  </select>
  <label>Choice 3</label>
  <select ng-model="food.fruitThree" ng-options="fruit.id as fruit.name for fruit in fruits | filter: food.fruitOne!=''?{id: '!' + food.fruitOne}:{} | filter: food.fruitTwo!=''?{id: '!' + food.fruitTwo}:{}">
    <option value=""></option>
  </select>
  <hr>
  <p>Choice 1 - {{ food.fruitOne }}</p>
  <p>Choice 2 - {{ food.fruitTwo }}</p>
  <p>Choice 3 - {{ food.fruitThree }}</p>
</body>

Upvotes: 1

Pritam Banerjee
Pritam Banerjee

Reputation: 18958

ng-options and option does not work together.

You need to use only one of them. Both of them do not work together in the same directive.

The best way to add some particular values is to have it included in the model. For that you will need to customize your filter. That's how I did it in project.

Change your model to this:

$scope.fruits = [
    {id: 4, name: ' '},
    {id: 1, name: 'apple'},
    {id: 2, name: 'banana'},
    {id: 3, name: 'orange'}
  ];

Upvotes: 1

Related Questions