Show an aggregated list in angularjs

后端 未结 2 2052
野性不改
野性不改 2020-12-30 05:24

In my model I have data similar to:

$scope.list = [{id:0,tags:[\'tag1\',\'tag2\']},{id:2,tags:[\'tag2\']}};

I want to show a list of tags (

2条回答
  •  爱一瞬间的悲伤
    2020-12-30 06:29

    Use a custom filter to get a unique set/array of tags, suitable for use with ng-repeat:

    .filter('uniqueTags', function() {
        return function(list) {
            var tags = {};
            angular.forEach(list, function(obj, key) {
                angular.forEach(obj.tags, function(value) {
                    tags[value] = 1;
                })
            });
            var uniqueTags = []
            for (var key in tags) {
                uniqueTags.push(key);
            }
            return uniqueTags;
        }
    });
    

    I first put the tags into an object, which automatically gives us uniqueness. Then I convert it to an array.

    Use as follows:

    Fiddle.


    The following may not do what I think you probably want/expect it to do:

    
    

    This does not create $scope properties filter.tag1 and filter.tag2 on the controller scope (i.e., the scope where ng-repeat is used). Each iteration of ng-repeat creates its own child scope, so the ng-model above will create scope property filter.tag on each ng-repeat child scope, as shown in my fiddle.

提交回复
热议问题