我想在加載後更改iframe的scrollTop。 這是我的想法。如何在angularJS中使用iframe
模板<iframe .. onload="{{loaded()}}" ..></iframe>
在控制器
$scope.loaded = function() {
//chage scroll of iframe
}
但我認爲這是沒有棱角的風格( 「請不要將任何類型的DOM操作」)
什麼是最好的做法做這個?
我想在加載後更改iframe的scrollTop。 這是我的想法。如何在angularJS中使用iframe
模板<iframe .. onload="{{loaded()}}" ..></iframe>
在控制器
$scope.loaded = function() {
//chage scroll of iframe
}
但我認爲這是沒有棱角的風格( 「請不要將任何類型的DOM操作」)
什麼是最好的做法做這個?
這裏是mycode。但跨域不工作..
directive('myIframe', function(){
var linkFn = function(scope, element, attrs) {
element.find('iframe').bind('load', function (event) {
event.target.contentWindow.scrollTo(0,400);
});
};
return {
restrict: 'EA',
scope: {
src:'@src',
height: '@height',
width: '@width',
scrolling: '@scrolling'
},
template: '<iframe class="frame" height="{{height}}" width="{{width}}" frameborder="0" border="0" marginwidth="0" marginheight="0" scrolling="{{scrolling}}" src="{{src}}"></iframe>',
link : linkFn
};
});
這可能是跨域破壞的原因。 https://github.com/angular/angular.js/issues/3679 – Nick
我知道這是一個老問題,但要擺脫跨域錯誤,您可以進行更改:'return {... scope.src:' &src'...}','template:'
@Miquel你可以用你的修改編輯這個答案或發佈一個新的答案,這樣其他人也可以從中受益。 – aProgrammer
像這樣的東西應該工作,只需在您的iframe標籤my-frame='loaded()'
,它應該工作。它沒有經過測試,我假設加載函數在加載框架後調用。如果它不起作用,也許ready
將工作。
.directive('myFrame',function(){
return {
link:function(scope,ele,attrs){
ele.load(function(){
scope.$apply(attrs.myFrame);
});
}
};
});
我發現'load'沒有工作,但'準備好了' – mblakele
這是一個解決辦法,以避免跨域問題:
directive('myIframe', function(){
var linkFn = function(scope, element, attrs) {
element.find('iframe').bind('load', function (event) {
event.target.contentWindow.scrollTo(0,400);
});
};
return {
restrict: 'EA',
scope: {
src:'&src',
height: '@height',
width: '@width',
scrolling: '@scrolling'
},
template: '<iframe class="frame" height="{{height}}" width="{{width}}" frameborder="0" border="0" marginwidth="0" marginheight="0" scrolling="{{scrolling}}" src="{{src()}}"></iframe>',
link : linkFn
};
});
在控制器($ SCE注入):
$scope.getSrc = function() {
return $sce.trustAsResourceUrl("http://example.com");
};
和.html:
<my-iframe src='getSrc()'>
指令將是最好的實踐即 –