developer10
developer10

Reputation: 1500

AngularJS: Current directive implementation uses templates directly from variables, any chance I can user templateUrl here?

My current directive implementation is such that I may not be able to use templateUrl:

  1. I store the templates in some variables
  2. There is a function getTemplate with an argument to decide which variable to return through switch statement
  3. The returned variable is then used like this:

My linker function:

var linker = function(scope, element, attrs){
    scope.$watch('networkCalled', function(value){
        if(value){
            // the below getTemplate returns for example: someTplVariable; 
            // which holds the HTML markup
            element.html( getTemplate(value) );
            $compile( element.contents() )(scope);
        }
    });
}

return {
    restrict: "A",
    replace: true,
    link: linker,
    scope: {
        content: "=",
        networkCalled: "="
    }

Is there any chance I can use templateUrl feature here? I have more than a few templates here so I want to move them into separate files.

On the other hand, if using templateUrl is not possible, then suggest another approach that would still enable me to dynamically set my template but via templateUrl.

Of course, if you need more code, let me know

Upvotes: 0

Views: 96

Answers (1)

acalfo
acalfo

Reputation: 61

You can do something nifty here to get dynamic template loading by setting your template to a ng-include with a 2 way bound variable as its url:

@note I'd typically put this linker code in a controller to get auto digest cycles on your url variable

var linker = function(scope, element, attrs){
//set default url. 
scope.url = getTemplate(<default-value>);
scope.$watch('networkCalled', function(value){
    if(value){
        // set url to my current template. (may need $apply())
        scope.url = getTemplate(value);
    }
});

}

return {
restrict: "A",
replace: true,
link: linker,       //dynamically include html from url var
template: "<div ng-include="url"></div>
scope: {
    content: "=",
    networkCalled: "="
}

Upvotes: 1

Related Questions