Brian Triplett Brian Triplett - 5 months ago 147
AngularJS Question

Dynamically assign templateUrl in angular component

I have an angular component I am building in angular 1.5. It looks like this:

var module = angular.module("ncRelationshipSearch");

module.component("relationshipSearch", {
templateUrl: <need to dynamically assign>,
controllerAs: "vm",
controller: ['config', function(config){
... config provider here knows about templateURL...
}
}


I need the templateUrl to be assignable somehow. I have a
config
provider that could supply the URL but I can't inject it at the point of component definition. Is there a way to get the URL in through the bindings or set it later in the controller?

Answer

You can have function for templateUrl where you can inject service/factory. You can actually inject config provider over the templateUrl function.

module.component("relationshipSearch", {
    templateUrl: function(config){
       //play here with service variables generate templateUrl
       //other code can also lie here. :)
       return config.myTemplatUrl;
    },
    controllerAs: "vm",
    controller: ['config', function(config){
         ... config provider here knows about templateURL...
    }
}