How do I only show an element if nested ng-repeat is not empty?

前端 未结 6 1936
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 11:01

I have a List of lists, created with a nested ng-repeat. Each outer ng-repeat contains a div with the label of its inner list (eg: \"Group A\"). I\'m now trying to create a

6条回答
  •  感动是毒
    2020-12-25 11:40

    Your plunkr was pretty complicated and hard to weed through so I re-created what you wanted using a fiddle. The general idea behind my approach is to filter out the items from the array, not the sub array. And only do the filtered items when the text changes. So here's the markup:

    {{ type.name }}
    • - {{ entry.name }}

    And here's the code:

    angular.module('app', [])
    
    function ParentCtrl($scope){
        $scope.filterText = "";
        $scope.types = [
            { name: "type1", entries: [{ name: "name1"}, { name: "name2"}, { name: "name3"}]},
            { name: "type2", entries: [{ name: "name1"}, { name: "name3"}, { name: "name3"}]},
            { name: "type3", entries: [{ name: "name1"}, { name: "name2"}, { name: "name5"}]},
                { name: "type4", entries: [{ name: "name4"}, { name: "name2"}, { name: "name3"}]}
        ];
    
        $scope.filteredTypes = [];
        $scope.updateTypes = function(){
            $scope.filteredTypes.length = 0;
            for(var x = 0; x < $scope.types.length; x++){
                if($scope.filterText === ""){
                    $scope.filteredTypes.push($scope.types[x]);    
                }
                else{
                    var entries = [];
                    for(var y = 0; y < $scope.types[x].entries.length; y++){
                        if($scope.types[x].entries[y].name.indexOf($scope.filterText) !== -1){
                           entries.push($scope.types[x].entries[y]);   
                        }                        
                    }
                    if(entries.length > 0){
                        $scope.filteredTypes.push({
                            name: $scope.types[x].name,
                            entries: entries
                        });
                    }
                }
            }
        }
        $scope.updateTypes();
    }
    

    Fiddle: http://jsfiddle.net/2hRws/

    The reason I'm creating a new array and not using an actual filter to remove the results is that angular doesn't like creating dynamic arrays on the fly in filters. This is because it doesn't assign $$hashKey and things just don't line up correctly when dirty checking. I got the idea of how to do what you needed from this topic on the matter: https://groups.google.com/forum/#!topic/angular/IEIQok-YkpU

提交回复
热议问题