$ sce.trustAsResourceUrl()全局

Fra*_*isc 42 angularjs

我该怎么做这样的事情: $sce.trustAsResourceUrl('URL_HERE');

在全球范围内,就像在主应用程序config()run()函数中一样,任何iFrame,img src等都URL_HERE可以使用吗?

文档在解释这一点时相当差.

Tom*_*cer 72

你可以使用过滤器.这些在全球范围内可用

angular.module('myApp')
  .filter('trustUrl', function ($sce) {
    return function(url) {
      return $sce.trustAsResourceUrl(url);
    };
  });
Run Code Online (Sandbox Code Playgroud)
<img ng-src={{ imageHref | trustUrl }}">
Run Code Online (Sandbox Code Playgroud)

  • 最佳解决方案+1 (4认同)

chr*_*riz 54

我刚从前一个答案中读到你的评论.不确定你是否找到了解决方案.看起来你正在寻找一种白名单式的东西.我最近发现这有$ sce的白名单功能.

取自$ SceDelegateProviderAngularJS文档:

angular.module('myApp', []).config(function($sceDelegateProvider) {
 $sceDelegateProvider.resourceUrlWhitelist([
   // Allow same origin resource loads.
   'self',
   // Allow loading from our assets domain.  Notice the difference between * and **.
   'http://srv*.assets.example.com/**']);
 })
Run Code Online (Sandbox Code Playgroud)

有了这个你可以在这样的iframe中进行字符串插值:

<iframe ng-src="{{ 'http://srv1.assets.example.com/' + url_asset }}"></iframe>
Run Code Online (Sandbox Code Playgroud)

  • 仍然想知道*和**之间的实际区别是什么...... :( (5认同)
  • @ahmednawazbutt这是不正确的.sce提供程序的角度源代码在这里:https://github.com/angular/angular.js/blob/0822d34b10ea0371c260c80a1486a4d508ea5a91/src/ng/sce.js#L621并且*表示*匹配零个或多个出现的任何其他字符比以下6个字符中的一个:'`:`','`/`','```','`?`','`&`'和'````.**匹配零个或多个*any*字符.因此,它不适合在方案,域等中使用,因为它会匹配太多. (2认同)

man*_*san 7

我也喜欢过滤器解决方案; 然而,在我正确注入$ sce之前,它对我不起作用...

app.filter('trustUrl', ['$sce', function ($sce) {
  return function(url) {
    return $sce.trustAsResourceUrl(url);
  };
}]);
Run Code Online (Sandbox Code Playgroud)