AngularJS ng-options to exclude specific object

时间秒杀一切 提交于 2019-12-22 04:38:23

问题


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>

回答1:


You should use filter.

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



回答2:


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/




回答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>



回答4:


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>


来源:https://stackoverflow.com/questions/26215274/angularjs-ng-options-to-exclude-specific-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!