当前位置: 动力学知识库 > 问答 > 编程问答 >

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>

网友答案:

You should use filter.

<select ng-options="everyCategory.name for everyCategory in allCategories | filter: { name: '!' + category.name }">...</select>
网友答案:

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/

网友答案:

Thanks to @Krause and @Kamil R for the answer, yet I found an issue when using their solution, as I've mentioned in previous comments, if there are 2 categories with one name as a substring of another, the filter will cross out both of them. For instance, categories like: candy candybar Using

filter: { name: '!' + category.name }

will filter both of them out, in order to make sure only one gets filtered, I ended up writing a custom filter:

app.filter('parentTaxonomyFilter', function(){
    return function(items, name){
        var arrayToReturn = [];        
        for (var i = 0; i < items.length; i ++){
            if (items[i].name != name) {
                arrayToReturn.push(items[i]);
            }
        }
        return arrayToReturn;
    };
});

and in html, I use the filter like this:

<select class="form-control" ng-init="taxonomy.parentTaxonomy=getParentTaxonomy(taxonomy)" ng-model="taxonomy.parentTaxonomy" ng-options="everyTaxonomy.name for everyTaxonomy in data.allTaxonomies|parentTaxonomyFilter:taxonomy.name">
    <option value="">select parent taxonomy</option>
</select>
网友答案:

Try this

<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">...</select>
      <option value="">Select parent category</option>
    </select>
  </th>
</tr>
分享给朋友:
您可能感兴趣的文章:
随机阅读: