Reusing Previously Instantiated Templates With Ng-include
Solution 1:
I found this question interesting. Short of putting the model in a service (which is probably the correct way), I don't think there is a built in way to cache templates with ng-include without using ng-repeat, as demonstrated in this fiddle.
<divng-controller="Ctrl"><selectng-model="template"ng-options="t.name for t in templates"><optionvalue="">(blank)</option></select>
url of the template: <tt>{{template.url}}</tt><hr/><divng-repeat="t in templates"ng-include="t.url"ng-show="template.name == t.name"></div></div>
As you point out, the downside of this solution is you end up with a lot of elements in the DOM.
For fun, I wrote a version of ng-include that caches the template element and reuses it. You still end up potentially creating just as many DOM nodes in the worst case, but since they are created only on-demand, and since only one is ever in the DOM at any given time, it should remain fairly efficient from an angular perspective.
Here is the fiddle for this directive.
.directive('cacheInclude', function ($compile, $http, $templateCache) {
return {
link: function (scope, element, attrs, ctrl) {
var cache = {};
var currentElement = element;
var replaceCurrent = function(cacheEntry) {
currentElement.replaceWith(cacheEntry);
currentElement = cacheEntry;
};
scope.$watch(function(){
return scope.$eval(attrs.src);
}, function () {
var src = scope.$eval(attrs.src);
if (!cache[src]) {
$http.get(src, {cache: $templateCache}).then(function (result) {
cache[src] = $compile(result.data.trim())(scope.$new());
replaceCurrent(cache[src]);
});
} else {
replaceCurrent(cache[src]);
}
});
}
}
})
It's not "built in", but I think it is a good middle ground solution. Note, the directive is "for example only" and still requires error handling, etc.
Post a Comment for "Reusing Previously Instantiated Templates With Ng-include"