Angular:Iframe指令中的src属性错误

Angular : src attribute bug in Iframe directive

本文关键字:src 属性 错误 Iframe 指令 Angular      更新时间:2023-09-26

我试图实现的Iframe指令有问题。

就我而言:模板:

<div class="externalIframe" iframe-src="external.html"></div>

指令:

angular.module('project.directives', [])
   .directive('externalIframe', ['$rootScope', function($rootScope) {
      return {
        restrict: 'C',
        replace: true,
        transclude: true,
        scope: {
          src: '@iframeSrc', // the src uses the data-binding from the parent scope
        },
        template: '<iframe src="{{src}}" height="100%" width="100%" frameborder="0"></iframe>',
        link: function(scope, elem, attrs) {
          //elem.src = "dummy.html"; // not working either
        }
      }
    }])

问题:它触发2个HTTP请求(2个iframe加载)。:

  • 一个到http://localhost:8000/app/{{src}}(iframe-src尚未由angular解释)
  • 一个到http://localhost:8000/app/external.html(iframe-src曾经被angular解释)

我想避免无用的第一个电话。。我该怎么做?

我尝试在模板中不使用src,并在链接或编译函数中以编程方式设置它,但这不会触发iframe加载。

编辑:jsFiddle添加了编译方法用于bug演示=>您将在firebug/chrome dev面板的网络选项卡中看到两个请求:

  • http://fiddle.jshell.net/_display/%7B%7Bsrc%7D%7D
  • http://fiddle.jshell.net/_display/external.html

感谢的帮助

您不需要指令。在实际的iframe元素上使用ng-src。请参阅ng src上的文档。

<iframe ng-src="external.html"></iframe>

从模板中的iframe中删除src并简单地更改链接函数中的属性(通过element.attr())就可以了:

return {
    restrict: 'E',
    require: '?ngModel',
    replace: true,
    transclude: true,
    template: '<iframe height="100%" width="100%" frameborder="0"></iframe>',
    link: function (scope, element, attrs) {
        element.attr('src', attrs.iframeSrc);
    }
};

Fiddle:http://jsfiddle.net/5rYrw/

不要使用'link',而是使用'compile'函数,因为您本质上想要在插入DOM之前修改HTML。我认为"链接"是插入的,然后绑定到作用域。

所以有了链接1.使用{{url}}调用compile-iframe发出请求2.链接被调用,{{url}}被替换,因此您进行了第二次调用。

如果使用"compile",则可以自己修改src属性。

给予http://docs.angularjs.org/guide/directive看一看,希望这能帮助

编辑检查这把小提琴http://jsfiddle.net/jbSx6/20/

return {
    restrict: 'E',
    require: '?ngModel',
    replace: true,
    transclude: true,
    template: '<iframe src="%url%" height="100%" width="100%" frameborder="0"></iframe>',
    compile: function (element, attrs, transclude) {
        console.log(element[0].outerHTML);
        element[0].outerHTML = element[0].outerHTML.replace('%url%',attrs.iframeSrc);
        console.log(element);
    }
};
<div ng-app="myApp">
   <div>display google in frame</div>
   <my-frame data-iframe-src="http://jsfiddle.net">test</my-frame>
</div>