James McConnell
James McConnell

Reputation: 2198

AngularJS filter on empty string

I have a simple Angular filter setup between a select and a list. When a user selects an item from the dropdown, the list is updated to show the matching result. The problem is that I have a "Select..." option first in the dropdown with no value, and when that is the selected value, all items are shown. I suppose that makes sense, but I want the opposite. If the selected option has no value, I don't want to show the list. Here are some relevant bits, followed by a link to a full fiddle:

The dropdown:

<select class="world-list" ng-model="selectedWorld" ng-options="world.worldId as world.worldName for world in allWorlds">
    <option value="">Select...</option>
</select>

The list:

<ul class="unstyled" id="charList">
    <li ng-repeat="char in characters | filter:selectedWorld">
        <a href="#" class="btn btn-block" ng-click="selectChar()">{{char.charName}} - {{char.charRace}} {{char.charClass}}</a>
    </li>
</ul>

And here is a link to the full fiddle, which contains my JSON structures that drives all this: http://embed.plnkr.co/6XUmC5efO0Y1BRNLRUig

What I'm trying to do is rather simple, and I'm pretty new to Angular so I'm sure I'm missing something obvious. Checked the Jabbr room, nobody on. :(

Anyway, thanks for any and all help!

Upvotes: 1

Views: 7068

Answers (2)

Javamav
Javamav

Reputation: 153

I noticed in your code "script.js" you don't seem to be accounting for the blank option.

I did not test this (I probably should prior to posing this answer), but it should work by placing the "blank" option within your script.js.

app.controller('WorldCtrl', function ($scope, $http) {
    $scope.allWorlds = [{
      worldId: "",
      worldName: ""
    },
    {
      worldId: "b8ee0530-744b-463e-9428-23178f6c7bff",
      worldName: "World 1"
    },
    {
      worldId: "81211982-5613-4f9c-b704-7b6fa35faf84",
      worldName: "World 2"
    },
    {
      worldId: "df41208e-e8d2-46c9-8299-8f37632a51f8",
      worldName: "World 3"
    }];

    $scope.characters = [{
      charClass: "Rogue",
      charName: "Vaes",
      charRace: "Human",
      worldId: "b8ee0530-744b-463e-9428-23178f6c7bff"
    },
    {
      charClass: "Warrior",
      charName: "Azash",
      charRace: "Orc",
      worldId: "b8ee0530-744b-463e-9428-23178f6c7bff"
    },
    {
      charClass: "Mage",
      charName: "Anele",
      charRace: "Ogre",
      worldId: "81211982-5613-4f9c-b704-7b6fa35faf84"
    }];
});

Upvotes: 0

Stewie
Stewie

Reputation: 60406

One way to accomplish this is to filter by specific properties of the iteration object:

<ul class="unstyled" id="charList">
  <li ng-repeat="char in characters | filter:{worldId: selectedWorld}">
    <a href="#" class="btn btn-block" ng-click="selectChar()">{{char.charName}} - {{char.charRace}} {{char.charClass}}</a>
  </li>
</ul>

Plunker

Upvotes: 3

Related Questions