Showing unique dropdown options in Angularjs

混江龙づ霸主 提交于 2019-12-08 13:50:35

问题


I have a following drop down which is working fine

                     <select class="form-control" ng-model="cc.id">
                       <option value="">Chose Id</option>
                       <option ng-repeat="account in accounts |unique:'id'" value="{{account.id}}">{{name.id}}</option>
                       </select>

It gives me following options in the dropdown

          101
          101
          119
          120
          121
          121

While it should be only showing the unique id in options as...

       101
       119
       120
       121

Accounts consists of jason array of Account which has act_id (primary key) id fname lname location

Can you please tell me how to fix the unique filter on id so that it displays only unique values Thanks


回答1:


AngularUI has exactly what you need, the ´unique´ filter.

Example:

ng-options="color in colors | unique:'name'"



回答2:


I would use uniq method from Underscore library.

And just write one row:

$scope.new_accounts = _.uniq(accounts, false, function(p){ return p.id; });

Demo Fiddle

Reference:

uniq_.uniq(array, [isSorted], [iterator]) Alias: unique Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.

_.uniq([1, 2, 1, 3, 1, 4]);
=> [1, 2, 3, 4]



回答3:


According to this AngularJS does not have a unique filter - AngularUI does.

The following code from the link above should help:

app.filter('unique', function() {
    return function(input, key) {
        var unique = {};
        var uniqueList = [];
        for(var i = 0; i < input.length; i++){
            if(typeof unique[input[i][key]] == "undefined"){
                unique[input[i][key]] = "";
                uniqueList.push(input[i]);
            }
        }
        return uniqueList;
    };
});

Also, you can use something like this:

<select ng-model="accounts" ng-options="c.name for c in accounts"></select><br>

for the select.



来源:https://stackoverflow.com/questions/21525967/showing-unique-dropdown-options-in-angularjs

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