Opinionated Angular style guide for teams by Fagner Silva Martins
If you are looking for an opinionated style guide for improve the performance of your project listing, conventions, and structuring Angular applications, then step right in. These styles are based on my development experience with Angular.
- To minimize creation of DOM elements in ngRepeat
- Optimize performace with One-time binding
- Optimize performace to ng-show, ng-hide, ng-if and ng-repeat
- References
[Style Y001]
- Always use
track byin ng-repeat.
Why?: ngRepeat will know that all other items already have DOM elements, and will not re-render them.
<!-- avoid -->
<div ng-repeat="model in collection">
{{model.name}}
</div><!-- recommended -->
<div ng-repeat="model in collection track by $index">
{{model.name}}
</div>[Style Y002]
- Use
limitToto avoid mass insertion in the list to be displayed.
Why?: Mass insertion causes a considerable delay in rendering leaving the feeling of slowness to the user.
<!-- avoid -->
<div ng-repeat="model in collection">
{{model.name}}
</div><!-- recommended -->
<div ng-repeat="model in collection | limitTo : limit track by $index">
{{model.name}}
</div>Note: The increment of the variable that determines the limitTo must be placed in the function that executes the next page.
[Style Y010]
- Use
::for considered a unique expression.
Why?: Using this expression avoids creating watches by decreasing rendering time.
<!-- avoid -->
<div ng-controller="EventController">
<p>Name: {{name}}</p>
</div> <!-- recommended -->
<div ng-controller="EventController">
<p>Name: {{::name}}</p>
</div>Caution: Do not use this expression for variables that can be updated while the page is displayed.
[Style Y020]
- Never call a function directly to
ng-show,ng-hideandng-ifdirectives.
Why?: The function will be called in all scope updates.
<!-- avoid -->
<div ng-show="myFunction()">
...
</div>Change your function to a variable
<!-- recommended -->
<div ng-show="showDiv">
...
</div>[Style Y021]
- Never call a function directly to
ng-repeatdirective.
Why?: As ng-show the function will be called in all scope updates.
<!-- avoid -->
<div ng-repeat="model in myFunctionGetCollection()">
...
</div>Change your function to a variable
<!-- recommended -->
<div ng-repeat="model in collection">
...
</div>For anything else, API reference, check the Angular documentation.