0
\$\begingroup\$

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';
                }
            };
        }
    };
});
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

To my opinion your 2nd way which uses ng-include is better because as mentioned in angular doc it says that-

The $templateRequest service runs security checks then downloads the provided template using $http and, upon success, stores the contents inside of $templateCache. If the HTTP request fails or the response data of the HTTP request is empty, a $compile error will be thrown.

Although $templateRequest factory that was added in v3.0. $templateRequest function checks and saves to the $templateCache.

Another way you can use

templateUrl: function(element, attributes) {  
  if (element[0].tagName === 'INPUT') {
    return 'templates/input.html';
  } else {
    return 'templates/default.html';
  }
}
\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.