I have recently upgraded to AngularJS 1.5 and as the title says, I want to use different templates
depending on a value in the item
object passed.
After some research I found multiple ways to accomplish my task and I have picked out two of the (many) ways I found. Since I'm still quite new at Angular I was curious about the best way to do it performance wise.
1st way
angular.module('MyModule').directive('myDirective',
['$templateRequest', '$compile', function ($templateRequest, $compile) {
return {
restrict: 'EA',
replace: true,
scope: {
item: '='
},
link: function (scope, element, attr) {
if (scope.item.component != null) {
scope.template = 'js/MyModule/directives/my-directive/my-component.html';
} else if (scope.item.question != null) {
scope.template = 'js/MyModule/directives/my-directive/my-question.html';
}
$templateRequest(scope.template)
.then(function(html){
var template = angular.element(html);
element.append(template);
$compile(template)(scope);
});
}
};
}]);
2nd way
angular.module('Testview').directive('learningPlayerBody', function () {
return {
restrict: 'EA',
replace: true,
template: '<div ng-include="getTemplateUrl()"></div>',
scope: {
item: '='
},
link: function (scope, element, attr) {
scope.getTemplateUrl = function() {
if (scope.item.component != null) {
scope.template = 'js/MyModule/directives/my-directive/my-component.html';
} else if (scope.item.question != null) {
scope.template = 'js/MyModule/directives/my-directive/my-question.html';
}
};
}
};
});