2017-08-24 39 views
0

我得到了兩個指令,一個指令是另一個指令的子指令。 在子指令中將會有一個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

回答

1

您可以使用過濾器代替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