angularjs 1.5 override templateUrl

682 views Asked by At

For a directive like below, is there a way to override the 'templateUrl' property so that instead of myTemplate1.tpl.html myTemplate2.tpl.html can be used? This is because the directive has already been used at other places but for a new requirement the current template cannot be used.

angular.module("myDirective", [])
    .directive("myDirective", [function () {
    "use strict";

    return {
        restrict: "E",
        replace: true,
        scope: {
            "property1": "=",
            "property2": "="
        },
        templateUrl: "web-url/myTemplate1.tpl.html"
    };
}]);
2

There are 2 answers

0
devqon On BEST ANSWER

If you can edit the directive code itself, you can do something like this:

angular.module("myDirective", [])
    .directive("myDirective", [function () {
    "use strict";

    return {
        restrict: "E",
        replace: true,
        scope: {
            "property1": "=",
            "property2": "="
        },
        templateUrl: function(element, attrs) {
            // default to 'old' template
            // only use other template if passed through the 'template-url' attribute
            return attrs.templateUrl || "web-url/myTemplate1.tpl.html";
        }
    };
}]);

This way all your old directive usages will still work, and you can configure it like this:

<!-- Still uses web-url/myTemplate1.tpl.html -->
<my-directive></my-directive>

<!-- Uses some/other/template/url.html -->
<my-directive template-url="some/other/template/url.html"></my-directive>
0
rsh On

Probably Try like below:

angular.module("myDirective", [])
    .directive("myDirective", [function () {
    "use strict";

    return {
        restrict: "E",
        replace: true,
        scope: {
            "property1": "=",
            "property2": "="
        },
        templateUrl:  function(elem, attr) {
            return 'web-url/myTemplate'+ attr.urlnum+'.tpl.html';
         }
    };
}]);