0

Good evening,

Is there any way to create a template that recursively shows a structure and has an onclick function on every item. This onclick function needs the current index including all parent indexes of this element (for example [0][2][1] for BMW in the list below).

A [0]
  Tree [0][0]
    ...
  House [0][1]
    ...
  Car [0][2]
    Mercedes [0][2][0]
    BMW [0][2][1]
    Audi [0][2][2]
    VW [0][2][3]
    Chrysler [0][2][4]
B [1]
  ...
C [2]
  ...

My current directives look like this but I have no idea how I cant get the FULL INDEX of every element for the ng-click function.

app.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            collection: '='
        },
        template: `
          <ul>
            <member ng-repeat='member in collection'
                    member='member' index='$parent.index + $index'>
            </member>
          </ul>`
    }
});

app.directive('member', function ($compile) {
    return {
        restrict: "E",
        replace: true,
        template: "<li ng-click=\"select(member)\">{{member.title}}</li>",
        link: function (scope, element, attrs) {
            var collectionSt = '<collection collection="member.sub"></collection>';
            if (angular.isArray(scope.member.sub)) {
                $compile(collectionSt)(scope, function(cloned, scope) {
                    element.append(cloned); 
                  });
            }
        }
    }
});
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • Using `replace: true` is asking for trouble. See [Why is `replace` property deprecated in AngularJS directives?](https://stackoverflow.com/questions/24194972/why-is-replace-deprecated-in-angularjs/35545445#35545445). – georgeawg Dec 08 '17 at 16:15

1 Answers1

1

In the controller, add a fullIndex property to each member and return that property as an argument of the ng-click function:

template: `<li ng-click="select(member.fullIndex)">{{member.title}}</li>`,

Having the template compute the fullIndex value with AngularJS expressions would make the app difficult to understand, debug, and maintain. It is better to do the computation in JavaScript.

georgeawg
  • 48,608
  • 13
  • 72
  • 95