Angular:Iframe指令中的src属性错误
Angular : src attribute bug in Iframe directive
我试图实现的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>
相关文章:
- 从其他元素上的单击事件访问image src属性
- 使用json数据更改视频标签中的src属性
- 为什么html src属性中的相对url是因为Javascript函数中的完整路径
- 无法在
标记 SRC 属性中传递参数
- 单击没有 src 属性的 iframe 中的元素
- img src 属性在为空时返回页面的 URL
- 如何从浏览器隐藏视频src属性's检查元素
- 为什么当我尝试为iframe-src属性构建URL时,AngularJS会抛出错误
- Windows Phone浏览器控件执行JS函数来替换src属性
- 使用jQuery通过更改src属性来设置一个图像标签的动画
- 使用angularjs中的自定义服务交换ng src属性
- 使用angularjs交换图像标签中的ng-src属性
- AngularJS - 如何在 iframe 元素更改时读取 SRC 属性
- 浏览器检测和 Firefox data-src 属性
- 延迟加载引导传送带而不更改 img src 属性
- 根据 JSON 更改图像的 src 属性
- 如何在 ajax 请求的回调中设置 ngInclude 元素的 src 属性
- 如何制作 AngularJS 指令来更改图像的 src 属性
使用 Jquery 不会更改 src 属性
- 修改其<源>元素的 src 属性后,视频不会更新