创建指令计数量

问题描述:

我得到了两个指令,一个指令是另一个指令的子指令。 在子指令中将会有一个ng-repeat。因此,将会有x个子指令的数量取决于它将重复的列表。我的问题是:基本指令是否可能知道将有多少个子指令?然后,base指令将知道何时将子指令的所有值连接起来并传递给它。创建指令计数量

在这个例子中,列表的$scope.length是已知的。但由于ng-if 3次指令的创建和$scope.length不是它的长度是5

<!DOCTYPE html> 
<html> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
<body ng-app="myApp"> 

<test-directive> 
    <test-sub-directive ng-repeat="l in list" ng-if="l > 2" variable="{{l}}">{{l}}</test-sub-directive> 
</test-directive> 

<script> 

var app = angular.module("myApp", []); 

    app.directive('testDirective', function() { 
    return { 
     restrict: 'E', 
     controllerAs: 'testCtrl', 
     controller: ['$scope', '$element', '$attrs', function testCtrl($scope, $element, $attrs) { 

     $scope.list = [1,2,3,4,5]; 

     this.testFunc = function() { 

      //When everything is fetched from the sub-directive send it to another function 
     } 
     }] 
    }; 
    }) 
    app.directive('testSubDirective', function() { 
    return { 
     require: '^test-directive', 
     restrict: 'E', 
     link: function (scope, element, attrs, testCtrl) { 


     testCtrl.testFunc(); 
     }, 
    }; 
    }) 
</script> 

</body> 
</html> 

https://www.w3schools.com/code/tryit.asp?filename=FIUXSWL47ZC9

您可以使用过滤器代替ng-if。现在您可以使用结果来确定父指令中的lengthThis is a working edit of your sample

+0

感谢它的工作,但我有一些限制,我不能从范围调用函数来修改我的数据列表。我必须保持这样:'ng-repeat =“l in list”' –

+0

然后在'list'上应用过滤器函数。类似于'ng-repeat =“l在list | filter中:”' – Murwa

+0

如果ng-repeat的输出与给定的输入一致,否则你将会遇到一个无限循环,并且角度会'呕吐' – Murwa