How to make ng-repeat filter out duplicate results

前端 未结 16 2665
鱼传尺愫
鱼传尺愫 2020-11-22 06:52

I\'m running a simple ng-repeat over a JSON file and want to get category names. There are about 100 objects, each belonging to a category - but there are only

16条回答
  •  清酒与你
    2020-11-22 07:09

    Add this filter:

    app.filter('unique', function () {
    return function ( collection, keyname) {
    var output = [],
        keys = []
        found = [];
    
    if (!keyname) {
    
        angular.forEach(collection, function (row) {
            var is_found = false;
            angular.forEach(found, function (foundRow) {
    
                if (foundRow == row) {
                    is_found = true;                            
                }
            });
    
            if (is_found) { return; }
            found.push(row);
            output.push(row);
    
        });
    }
    else {
    
        angular.forEach(collection, function (row) {
            var item = row[keyname];
            if (item === null || item === undefined) return;
            if (keys.indexOf(item) === -1) {
                keys.push(item);
                output.push(row);
            }
        });
    }
    
    return output;
    };
    });
    

    Update your markup:

    
    

提交回复
热议问题