在动态 templateUrl 指令中使用 promise

Use promise in directive for dynamic templateUrl

我有一个 SharedData 承诺,它 return 也是一个可变服务 .template。该值为 mytemplate,我用它构建了一个 url,我想将其传递给 templateUrl 指令但没有成功。

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
}
});

谢谢你的帮助!

The docs seem to say that the templateUrl can be set asynchronously. 但是,我无法证明这适用于 promises。因此,您可以在仍然使用承诺的同时执行此操作的一种方法是将模板添加到 link 函数中的元素。

看起来像这样。

  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. 它假定模板已加载到 $templateCache,因此如果不是,您可以执行 $http.get() 以获得相同的效果。

我使用 $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
            });
        });
      }
    };
});

这是一个Plunker

希望这会对一些人有所帮助 :) 并感谢@Matthew Green