Home > Mobile >  AngularJS loads constructor multiple times
AngularJS loads constructor multiple times

Time:07-28

my controller is loaded multiple times in my AngularJS 1.5 code:

<div ng-repeat="conditionForMultipleRows"> 
 <div data-ng-if="$first">
   <div co-my-component></div>
 </div>
</div>
export function coMyComponent(): ng.IDirective {
  return {
    template: coMyComponentTemplateHtml,
    controller: 'MyComponentController',
    controllerAs:'$ctrl'
  }
}

export class MyComponentController{

state: MyStateClass;
static $inject = [someServices]
constructor(someServices) {
 document.getElementById("myComponent").addEventListener("myEvent", (ev: CustomEvent) => {
 doStuff()
}
    

The HTML Part is only called once, so there should be no issue. Only my controller is loaded multiple times. The angular.module only loads the controller once and the directive only once, so there is no issue. Also there is no other place where the controller or webcomponent is called in the code.

I'm not very familiar with AngularJS so you can also point out other parts if you see something wrong here. Please refer to a source if it was resolved there. I didnt find any helpful answer

Thanks in advance guys

CodePudding user response:

Each time your directive is instantiated, it will received a brand new controller.

The ng-repeat directive instantiates a template once per item from a collection. In your case, if conditionForMultipleRows is an array having four items inside, you will instantiate four times the template

<div data-ng-if="$first">
   <div co-my-component></div>
</div>

Each template instance gets its own scope and own controller, thus calling the constructor four times.

CodePudding user response:

The answer for my issue here is:

<div ng-repeat="conditionForMultipleRows track by $index "> 
 <div data-ng-if="$first">
   <div co-my-component></div>
 </div>
</div>

With adding track by $index, the controller of my component only loaded once. Also learned that in a ng-repeat it should always be added a "track by". There are only a few egde cases where this isnt required. Correct me if I'm wrong

  • Related