Recursion in Angular directives

前端 未结 9 1508
不思量自难忘°
不思量自难忘° 2020-11-22 04:24

There are a couple of popular recursive angular directive Q&A\'s out there, which all come down to one of the following solutions:

  • manually incrementally \
9条回答
  •  情深已故
    2020-11-22 04:32

    There is a really really simple workaround for this that does not require directives at all.

    Well, in that sense, maybe it is not even a solution of the original problem if you assume you need directives, but it IS a solution if you want a recursive GUI structure with parametrized sub-structures of the GUI. Which is probably what you want.

    The solution is based on just using ng-controller, ng-init and ng-include. Just do it as follows, assume that your controller is called "MyController", your template is located in myTemplate.html and that you have an initialization function on your controller called init that takes argument A, B, and C, making it possible to parametrize your controller. Then the solution is as follows:

    myTemplate.htlm:

    Hello

    I found by plain conincidence that this kind of structure can be made recursive as you like in plain vanilla angular. Just follow this design pattern and you can use recursive UI-structures without any advanced compilation tinkering etc.

    Inside your controller:

    $scope.init = function(A, B, C) {
       // Do something with A, B, C
       $scope.D = A + B; // D can be passed on to other controllers in myTemplate.html
    } 
    

    The only downside I can see is the clunky syntax you have to put up with.

提交回复
热议问题