Order AngularJS directives are created not as I understand from the documentation

108 Views Asked by At

I have an AngularJS app where I have to traverse some of the elements with the cursor keys. To do this I created a directive called selectable that adds some info to a list in a service when the directive is created.

It is important that this happens in the order that the selectable directives appear in the view.

From my research:

Directive compilation step by step and other

I thought that this would work because pre-link and controllers would be created in order. But this does not always happen.

Here is my HTML:

<selectable ng-repeat="suggestion in pCtrl.suggestions" value="suggestion">
  {{suggestion}}
</selectable>
<div ng-repeat="cat in pCtrl.categories">
  <selectable ng-repeat="item in cat" value="item">
    {{item}}
  </selectable>
</div>
<selectable ng-if="true" value="pCtrl.bottom">
  <div>
    Bot content
  </div>
</selectable>

And here the directive:

app.directive('selectable', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {},
    controller: 'SelectableCtrl',
    controllerAs: 'selCtrl',
    bindToController: {
      value: '='
    }
  };
})
.controller('SelectableCtrl', [
  function() {
    var self = this;
    console.log(this.value);
  }
]);

What I see in the console log is that the bottom selectable with the ng-if is created just after the first ng-repeat and then the rest of the ng-repeats are created.

I made a plunker to demonstrate what happens. Please check the console log of the plunker.

Plunker: Directive creation order test

1

There are 1 best solutions below

2
On BEST ANSWER

In angular JS Compilation order of nested directives based on priority the deeper the element nested, the later it is compiled.

In your code selectable for the Categories are nested in the div div ng-repeat="cat in pCtrl.categories"

first the selectable directives which are present in the outer div tag gets compiled and then remaining selectable directive which is present in inner div tag gets compiled. Hence the console output showing the order as per its compilation.