在动态templateUrl的指令中使用promise

时间:2015-05-07 16:28:31

标签: javascript angularjs angularjs-directive angular-promise

我有一个承诺SharedData,它也返回一个变量服务.template。值是mytemplate,我用它来构建一个url,我将传递给templateUrl指令,但没有成功。

print list(mytable.filter((Row.val3 == 7) and (Row.val2 == 2)))
# this only evaluates the second condition, instead of both conditions, printing:
# [[1, 2, 3, 'hello'], [1, 2, 7, 'cat'], [1, 2, 3, 'hi']]

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

The docs seem to say that the templateUrl can be set asynchronously.但是,我无法证明这适用于承诺。因此,在使用保证时,您可以执行此操作的一种方法是将模板添加到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()同样的效果。