Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use promise in directive for dynamic templateUrl

I have a promise SharedData which return a variable service .template as well. The value is mytemplate with which I build an url that I ant to pass to templateUrl directive but without success.

app.directive('getLayout', function(SharedData) {

var buildUrl= '';

SharedData.then(function(service) {
    buildUrl = service.template + '/layouts/home.html';
    console.log(buildUrl); // return mytemplate/layouts/home.html which is the URL I want to use as templateUrl
});

return {
    restrict: 'A',
    link: function(scope, element, attrs) {...},
    templateUrl: buildUrl
}
});

Thanks for helping me!

like image 424
Greg Avatar asked Sep 29 '22 00:09

Greg


2 Answers

I resolve my issue using $templateRequest

app.directive('getLayout', function($templateRequest, SharedData) {

return {

    restrict: 'A',

    link: function(scope, element, attrs) {

        SharedData.then(function(service) {

            myTemplate = $templateRequest(service.template + '/layouts/home.html');

            Promise.resolve(myTemplate).then(function(value) {
                element.html(value);
            }, function(value) {
                // not called
            });
        });
      }
    };
});

Here is a Plunker

Hope this will help some people :) and thanks to @Matthew Green

like image 189
Greg Avatar answered Nov 15 '22 04:11

Greg


The docs seem to say that the templateUrl can be set asynchronously. However, I have not been able to show that applies to promises. So one way you can do this then while still using a promise would be to add the template to your element in the link function instead.

That would look something like this.

  app.directive('getLayout', function($templateCache, SharedData) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        SharedData.then(function(templateName) {
          element.html($templateCache.get(templateName));
        });
      }
    }
  });

Here is a plunkr to show a full working example. It assumes that the template is loaded into $templateCache so if it isn't you can do a $http.get() for the same effect.

like image 33
Matthew Green Avatar answered Nov 15 '22 05:11

Matthew Green