[Fixed]-Testing AngularJS Directive with Karma & Dynamic Template URL

1πŸ‘

βœ…

In the past I’ve taken this approach to using dynamic template urls in my directives:

<div data-your-directive data-template-url="'partials/other.html'"></div>

passing the url as an optional attribute that will override the default if provided. Within my directive I then have:

angular.module('directives').directive('yourDirective', [function() {
    return {
        templateUrl: function($element, $attrs) {
            // Default template path.
            var templateUrl = 'partials/default.html';

            // Check if a template url attribute has been passed in to the 
            // directive. If one has been provided then make use of this
            // rather than the default.
            if ($attrs.templateUrl !== undefined) {
                templateUrl = $attrs.templateUrl;
            }

            return templateUrl;
        }
    };
}]);

This approach may prove to be easier for you to test.

Leave a comment