【问题标题】:AngularJS Directive - Error while interpolatingAngularJS 指令 - 插值时出错
【发布时间】:2017-03-24 14:57:00
【问题描述】:

我正在发现 AngularJS 指令,但我遇到了将对象的属性绑定到模板的问题。

我有一个不同内容类型(jpg、mp4)的项目列表,我正在尝试通过在有关内容类型的 img 标签和 video 标签之间切换来自定义 DOM。

我有一个控制器,它使用工厂作为从上一个视图中获取选定对象的依赖项:

app.controller('EventDetailCtrl', function($scope, Events) {
   $scope.event = Events.getCurrentEvent();
}

然后,我有我的指令:

angular.module('starter.directives', [])
.directive('myEventDirective', ['$compile', 'API_ENDPOINT', function($compile, API_ENDPOINT){
  var imgTemplate = '<img ng-src="' + API_ENDPOINT.url + '/events/image/{{event._id}}" />';

  var videoTemplate = '<video controls="controls" preload="metadata" webkit-playsinline="webkit-playsinline" class="videoPlayer">' + 
    '<source src="' + API_ENDPOINT.url + '/events/video/{{event._id}}" type="video/mp4"/> </video>';

  var getTemplate = function(contentType){
    var template = '';
    if(contentType == 'mp4'){
       template = videoTemplate;
    } else { 
     template = imgTemplate; 
    }
    return template;
  };

  return {
    restrict: 'E',
    replace: true,
    link: function(scope, element, attrs){
      console.log(scope.event);
      element.html(getTemplate(scope.event.contentType));
      compile(element.contents())(scope);
    }
  }
}]);

在我的 console.log(scope.event) 上,浏览器正在打印对象及其所有属性(_id、contentType、文件名等)。

还有我的 HTML 视图,我想在其中更新关于内容类型的标签:

<ion-view view-title="{{event.name}}">
  <ion-content class="padding">
   <my-event-directive data-source="event"></my-event-directive>
   <ion-item>
     Information about event do write
   </ion-item>
<ion-view />

但是我有错误信息:

错误:[$interpolate:noconcat] 插值时出错:http://192.168.1.11:8100/api/events/video/{{event._id}} 严格的上下文转义不允许在需要可信值时连接多个表达式的插值。

我已经尝试将属性范围添加到指令的返回对象,但是我有一个未定义的对象...

感谢您的帮助!

编辑:

我在互联网上发现问题出在视频 url 上(它是针对 XSS 攻击的一种保护),但我不知道如何自定义我的 DOM 的这一部分并避免任何安全漏洞..

【问题讨论】:

    标签: javascript angularjs data-binding angularjs-directive angularjs-interpolate


    【解决方案1】:

    您可以使用 $sce 服务返回可信资源。

    在 src 中提供一个来自您的作用域的函数,该函数将返回一个受信任的资源 URL。

    $scope.getResourceURL() {
        return $sce.trustAs($sce.RESOURCE_URL, yourURLhere);
    }
    

    文档:https://docs.angularjs.org/api/ng/service/$sce

    【讨论】:

    • 谢谢!只是管理做处理它。我将源标记中的属性 src 替换为 ng-src={{resourceUrl}} 并使用 $sce.trustAsResourceUrl(myURL); 直接在我的控制器中构建我的 URL;方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多