2013-08-21 68 views
6

我遇到了Iframe指令的問題,我嘗試實現。Angular:Iframe指令中的src屬性錯誤

據我: 模板:

<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由角尚未interpreated)
  • 一個http://localhost:8000/app/external.html(IFRAME SRC一旦被角interpreated)

我想避免無用的第一個電話。如何我可以這樣做嗎?

我試着沒有在模板中的src,並以編程方式將其設置在鏈接或編譯功能,但不會觸發iframe加載。

編輯:jsFiddle添加了錯誤的演示與編譯方法 =>你會螢火/ Chrome瀏覽器開發小組的網絡選項卡中有兩個請求是由看到:

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

感謝您的幫助

回答

8

你不需要這個指令。在iframe元素上使用ng-src。請參閱docs on ng-src

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

當然。你可以這樣做,但它沒有解決問題。 –

+0

你能向我解釋:我錯過了什麼?有什麼不同?如果你想要一個帶有iframe的指令,你仍然可以使用ng-src? – markmarijnissen

+0

使用ng-src工作起來就像一個魅力一樣,從一開始就讓兩個HTTP錯誤消失了。我認爲答案完全符合 –

1

而不是使用'鏈接'使用'編譯'功能,因爲你基本上想要在插入到DOM之前修改HTML。我認爲'鏈接'被插入,然後綁定到範圍。

所以帶鏈接 1.使用{{url}}調用編譯 - 通過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> 
+0

嗨,感謝您的幫助,但我嘗試過沒有成功。有關詳細信息,請參閱我的編輯/ jsfiddle。 –

+0

嗨比西 - 它確實有效,在那個小提琴中你仍然在使用鏈接功能,而不是編譯。請參閱我的編輯。 – leon

+0

這絕對是解決問題的「角度方式」。好答案。 –

5

模板從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); 
    } 
}; 

小提琴: http://jsfiddle.net/5rYrw/

+0

謝謝你,'element.attr('part was usefull。 –