I am using Directives to separate my code into templates, and I want those templates to load based on an if condition. Right now, when I look into the network traffic, Angular is sending all of the templates to the client regardless of if the ng-if
condition is met.
<div class="container">
<ul>
<template1 ng-if="taskCategory == 'condition1'"></template1>
<template2 ng-if="taskCategory == 'condition2'"></template2>
<template3 ng-if="taskCategory == 'condition3'"></template3>
</ul>
</div>
Here is an example of one of my directive templates:
/* Directive Template */
.directive('template1', [function() {
return {
restrict: 'E',
templateUrl: 'view/templates/template1.tpl.html'
};
}])
Is this expected behavior? It is working visually as expected. But I was under the impression with ng-if
data would lazy load based on the condition. Or am I misunderstanding how to use ng-if
?
That is definitely expected behavior. ng-if
will conditionally remove elements from the DOM based on the condition. The element is still rendered prior to being removed (otherwise a clone of the element is added back into the DOM).
The behavior is stated in the first paragraph in the AngularJS: ngif documentation.
'view/templates/template1.tpl.html'
will be loaded during the compile/link phase of the 1st view that uses the template1
directive.
The html response (nothing more than text in this stage) will be cached inside $templateCache (angular does that by default) and there will never be a second ajax until a full page refresh.
Even in this case, the next ajax call will be served from the browser cache and you may only see a 304 Not Modified. Since htmls are static files, they should be served with proper cache options (e.g. ETag header) and make sure they get reloaded if you change the code (with out asking users to clear their temporary files).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With