jsheffers
jsheffers

Reputation: 1622

Default "All" option not working on ng-option select list

I'm using a nested component structure and I'm having trouble getting the default "All" option to work on an ng-option generated select list. I've added a plunker to the bottom of this page. If I inspect the scope of the generated list I see that the "All" is returning null instead of an empty string. Plunker added below.

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

app.component('keyfeed', {
  bindings: { 
    search: '='
  },
  template: `
    <ul>
    <li ng-repeat="record in records | filter:$ctrl.search">{{ record.name }}</li>
    </ul>
  `,
  controller: function($scope) {
    
    $scope.records = [
      {
        "name": "Alfreds SFutterkiste",
        "id": "1",
        "tag": "tag1"
      },
      {
        "name": "Berglunds snabbköp",
        "id": "2",
        "tag": "tag1"
      },
      {
        "name": "Centro comercial Moctezuma",
        "id": "3",
        "tag": "tag2"
      },
      {
        "name": "Ernst Handel",
        "id": "4",
        "tag": "tag2"
      }
    ];
  }
});

app.component('search', {
  bindings: { 
    search: '='
  },
  template: `
    <select ng-model="$ctrl.search" ng-options="tag.name as tag.name for tag in $ctrl.tags">
    <option value="">All</option>
    </select>
  `,
  controller: function($scope) {

    this.tags = [
      {
        "tid": "1",
        "name": "tag1"
      },
      {
        "tid": "2",
        "name": "tag2"
      }
    ];
  }

});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link data-require="bootstrap-css@*" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.6.4/angular.js" data-semver="1.6.4"></script>
    <script src="script.js"></script>
</head>

  <body>
    <search search="search"></search>
    <keyfeed search="search"></keyfeed>
  </body>

</html>

As you can see in the plunker below, filtering by the tags is working. Unfortunately after you've selected a tag and you re-select All the list becomes empty.

Plunker

http://plnkr.co/edit/JkDGmOmEnW6T3iZXwdoX?p=preview

Upvotes: 1

Views: 255

Answers (1)

Nathan Beck
Nathan Beck

Reputation: 1191

Try this out:

http://plnkr.co/edit/V9Ztuhpbe21ewvaNB5tq?p=preview

You'll notice two things: 1) code in the select needs to become ng-options="tag.tid as tag.name for tag in tags" (not $ctrl.tags since tags array was bound to the components $scope).

2) an "All" option added to the dropdown with tid = ''. Using an empty string combined with filter:{ tag: $ctrl.search } will match everything. It's good to tell the filter to match against only a records tag too in the unlikely scenario that you have a tid in another property of the record.

Upvotes: 2

Related Questions