Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-options to exclude specific object

I'm using angular ng-options to show a with several options as the choices of parent category of the current category, basically these options contain all the existing categories, and I need to exclude the current category from ng-options, which quite make sense because a category cannot be the parent category of itself. So how do I do that? Currently I have the following code:

<tr ng-repeat="category in allCategories">
    <th ng-bind="category.name"></th>
    <th>
        <select ng-options="everyCategory.name for everyCategory in allCategories">
            <option value="">Select parent category</option>
        </select>
    </th>
</tr>
like image 327
dulan Avatar asked Oct 06 '14 11:10

dulan


People also ask

How do I filter with Ng-options?

In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.

What is Ng option AngularJS?

AngularJS ng-options Directive The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.

How do I set default value in ng-options?

In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.

What is ngInit?

The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.


2 Answers

You should use filter.

<select ng-options="everyCategory.name for everyCategory in allCategories | filter: { name: '!' + category.name }">...</select>
like image 179
Kamil R Avatar answered Oct 07 '22 08:10

Kamil R


You could use a filter

<tr ng-repeat="category in allCategories">
  <th>{{category.name}}</th>
  <th>
    <select ng-options="everyCategory.name for everyCategory in allCategories | filter: {name: '!' + category.name}" ng-model="somthing">
      <option value="">Select parent category</option>
    </select>
  </th>
</tr>

I've created a small fiddle with a exmaple of how to use it: http://jsfiddle.net/krausekjaer/tnqrqk2w/3/

like image 23
Krause Avatar answered Oct 07 '22 08:10

Krause