AngularJS: how to optimize nested directives

I have the following template for a directive item

in angular. The element contains a property type

in it. Based on this type, I need to render another template.

<item ng-repeat="myItem in items track by myItem.id">
  <div ng-switch="::myItem.type">
    <div ng-switch-when="type1">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type2">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type3">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type4">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type5">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type6">
      Some complex html with a couple of ng-if and ng-include
    </div>
  </div>
</item>

      

I would like to rework each ng-switch-when

in a standalone directive and improve the performance of ng-repeat (right now it has to do ng-include and set innerHTML for each element, and this is a heavy operation for the browser even for a list of 50 elements).

So my questions are:

  • how to recycle ng-switch-when into standalone directives
  • how to improve the performance of ng-repeat in this case

Update:

  • AngularJS related question : Parsing HTML events on the timeline is one of the reasons why I would like to optimize the current structure.
  • added missing track by

  • a lot of operators are required ng-if

    and ng-include

    because each widget presented ng-switch-when

    has its own logic and will be displayed based on some other parameters myItem

    .

The problem is also that I need to completely rebuild this list of items with some user action.

BTW:

In response, I can do something like:

render: function() {
  //it for two items, but can be extended for any number of templates
  var child = this.props.type === 'Type A' ? <TemplateA /> : <TemplateB />;

  return child;
}

      

+3


source to share


1 answer


I don't know why you need a lot of IF statements and why you want to use directives for this, but I can help you with advice for ng-repeat.

Use track by $index

in ng-repeat for better performance. And check out articles on Angular performance, for example: 11 Tips to Improve AngularJS Performance



Also, if you have an interface with many elements to render, you might want to look into ReactJS which is faster to render.

0


source







All Articles