ng-inline
ng-inline copied to clipboard
Using this algorithm for remote templates
The tests you demonstrate are quite amazing when compared to the stock Angular's ng-include.
I would really like to have this advantage because I do tend to split a lot of my HTML to separate templates for the sake of making them more manageable.
Now, I know this was designed specifically for inline templates, but despite that, I was wondering if it's technically possible to use the same method also for when templates are remote-fetched? Or is all the performance gain only the result of loading them the inline way?
Thanks.
Still looking for the perfect Angular (1.x), Dor.
Hey Shtaif, I just don't really know how this would work -- not to say it can't though. Do you have something specific in mind? I'll mull it over and perhaps take a stab at it this weekend. Cheers.
I implemented it, but I had to go back to the first implementation of the article, with compile phase. I guess it is a different use case, actually. Still, the resulting code is faster than with ng-include, so it is worth using for us.
class OptimInclude implements ng.IDirective {
public restrict: string = "EA";
public priority: number = 400;
private $templateRequest: ng.ITemplateRequestService;
private $compile: ng.ICompileService;
public static factory(): ng.IDirectiveFactory {
const directive: ng.IDirectiveFactory = ($templateRequest, $compile) =>
new OptimInclude($templateRequest, $compile);
directive.$inject = [ "$templateRequest", "$compile" ];
return directive;
};
constructor($templateRequest: ng.ITemplateRequestService, $compile: ng.ICompileService) {
this.$templateRequest = $templateRequest;
this.$compile = $compile;
}
public link: ng.IDirectiveLinkFn =
(scope: ng.IScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes): any => {
// <div optim-include="foo.html"></div>
// or
// <optim-include src="foo.html"></optim-include>
const templateUrl = attributes["optimInclude"] || attributes["src"];
if (!templateUrl) {
throw new Error("optim-include directive must have a URL");
}
this.$templateRequest(templateUrl)
.then((template: string) => {
element.html(template);
this.$compile(element.contents())(scope);
})
.catch((error: any) => {
console.error("Unable to get template for " + templateUrl, error);
});
};
}
The code is using TypeScript but it is rather trivial to go back to pure JS if needed. (NB : Optim / optim- is a silly prefix, just replacing our internal prefix; just replace with whatever fits your taste.)