AngularJS组件与外部托管的templateUrl?

时间:2017-08-22 20:42:58

标签: javascript angularjs

我有一个AngularJS应用程序,我将其作为插件加载到另一个具有不同路径的页面中。因此,我的模板URL必须完全限定,才能将其解析为正确的文件。但是,我收到Error: $sce:insecurl Processing of a Resource from Untrusted Source Blocked

我尝试使用resourceUrlWhitelist,但这并没有让我的错误消失,所以我想我会尝试trustAsResourceUrl。但是,我不知道如何将其与我的组件定义结合起来。

这是我的组件:

angular
  .module('synthApp')
  .component('foo', {
    templateUrl: 'http://example.com/app/components/main.template.html',
    controller: MainController
  });

function MainController() {
  ...
}

我尝试了以下操作,但收到$sce未知的错误:

angular
  .module('synthApp')
  .component('foo', ['$sce', {
    templateUrl: $sce.trustAsResourceUrl('http://example.com/app/components/main.template.html'),
    controller: MainController
  }]);

function MainController() {
  ...
}

在这种情况下使用trustAsResourceUrl的正确方法是什么?感谢。

1 个答案:

答案 0 :(得分:3)

component接受一个普通对象。它不能用于directive之类的DI。 .component('foo', ['$sce', { ... }])对于任何类型的DI(不仅仅是Angular)都不是正确的语法,因为它不涉及可以注入依赖关系的函数。

this answer中所述,templateUrl可以启用DI功能。

应该是:

angular
  .module('synthApp')
  .component('foo', {
    templateUrl: ['$sce', function ($sce) {
      return $sce.trustAsResourceUrl('http://example.com/app/components/main.template.html');
    }],
    controller: MainController
  });