Kenny
Kenny

Reputation: 177

angular select show name and item

I have following item, I want to show in a select-tag:

    [var objects = {name:name1, items:2}, {name:name2, items:3}, {name:name3, items:0}]

The code I want to create is:

    <select>
        <option value="name1">name1 [2]</option>
        <option value="name2">name2 [3]</option>
    </select>

In short, this will show the objects that have at least one 1 item. I've been trying to fix this in AngularJS and I have following code:

   <select ng-model="data.object" 
      ng-options="object.name as object.name [object.items] 
      when object.items > 0 for object in objects">
   </select>

Upvotes: 2

Views: 1583

Answers (1)

Jaydo
Jaydo

Reputation: 1859

I wasn't sure if you wanted to hide or disable options which have 0 items so here are some examples of both using ngOptions and without ngOptions.

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

app.controller("controller", function($scope) {
  $scope.selectedOption = "";

  $scope.objects = [{
    name: "name1",
    items: 2
  }, {
    name: "name2",
    items: 3
  }, {
    name: "name3",
    items: 0
  }];
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">

  <pre>Selected option: {{selectedOption}}</pre>

  <h3>ngOptions w/ disabled</h3>
  <select ng-model="selectedOption" ng-options="object.name as (object.name + ' [' + object.items + ']') disable when (object.items == 0) for object in objects">
    <option value=""></option>
  </select>

  <h3>ngOptions w/ filtered array</h3>
  <select ng-model="selectedOption" ng-options="object.name as (object.name + ' [' + object.items + ']') for object in objects | filter:{items: '!0'}">
    <option value=""></option>
  </select>

  <h3>Options w/ ngRepeat and ngIf</h3>
  <select ng-model="selectedOption">
    <option value=""></option>
    <option ng-repeat="object in objects" value="{{object.name}}" ng-if="object.items > 0">
      {{object.name + ' [' + object.items + ']'}}
    </option>
  </select>

  <h3>Options w/ ngRepeat and ngDisabled</h3>
  <select ng-model="selectedOption">
    <option value=""></option>
    <option ng-repeat="object in objects" value="{{object.name}}" ng-disabled="object.items == 0">
      {{object.name + ' [' + object.items + ']'}}
    </option>
  </select>

</div>

Upvotes: 1

Related Questions