AngularJS multiple expressions concatenating in interpolation with a URL

前端 未结 4 2129
太阳男子
太阳男子 2020-11-29 04:50

I know this is long, but please bear with me. The problem is easy to understand, just takes some writing to fully explain it.

Right now I\'m getting this error

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 05:38

    An alternative to @tasseKATT's answer (which doesn't require a controller function) is to use string concatenation directly in the expression a filter:

    angular.module('myApp')
      .filter('youtubeEmbedUrl', function ($sce) {
        return function(videoId) {
          return $sce.trustAsResourceUrl('http://www.youtube.com/embed/' + videoId);
        };
      });
    

    I've found this particularly useful when using SVG icon sprites, which requires you to use the xlink:href attribute on the SVG use tag - this is subject to the same SCE rules. Repeating the controller function everywhere I needed to use a sprite seemed silly so I used the filter method instead.

    angular.module('myApp')
      .filter('svgIconCardHref', function ($sce) {
        return function(iconCardId) {
          return $sce.trustAsResourceUrl('#s-icon-card-' + iconCardId);
        };
      });
    
    
    

    Note: I had previously tried just simple string concatenation inside the expression. However this led to some unexpected behaviour where the browser would interpret the expression before Angular had a chance to parse it and replace with the real href. Since there is no ng-src equivalent for the use tag's xlink:href I opted for the filter, which seems to have solved the issue.

提交回复
热议问题