我是Angularjs的新手,所以對你們中的很多人來說,這可能是一個非常明顯的問題。
我有一個 "main "視圖和一個 "MainCtrl "控制器。該控制器有一個"$scope.init() "函式,當控制器被初始化時被呼叫。 然而,我在視圖中有一個iFrame,它需要在 "init "函式成功運行之前完成其 "onload "js函式。
我嘗試使用iFrame的ngInit來觸發 "init "函式,但這發生在 "onload "之前
。請告訴我如何在iFrame的onload="otherFunction "結束后使init函式運行?
uj5u.com熱心網友回復:
在下面創建了一個演示,其中ng-init="encreateCount()"增加了$scope.carCount變數的值,但只是在<iframe>被加載之后。
你可以通過點擊按鈕來加載<iframe>,并觀察$scope.carCount如何變化。
雖然不確定這是否是正確的方法。
基本上,我在我的 INIT 函式內有 2 個函式,名為 increaseCount():
- 一個函式
increaseCount,包含主要的INIT邏輯,即增加汽車數量 。
- 一個函式
onIframeLoad,等待直到iframe被加載,然后通過呼叫increaseCount()執行主要的INIT邏輯;
互動式演示或運行下面的代碼↓↓↓
< 。var app = angular.module('App'/span>, [] );
//允許從各種來源加載iframe。
app.config(["$sceDelegateProvider"/span>, function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
//允許同源的資源加載。
"self"。
//允許YouTube iframes。
"https://www.youtube.com/embed/**"。
]);
}]);
//允許在HTML中使用 "iframe-onload "指令。
app.directive('iframeOnload', [function(){
return {
scope: {
callBack: '&iframeOnload'。
},
link: function(scope, element, attrs){
element.on('load', function() {
return scope.callBack()。
})
}
}}]);
//主控制器
app.controller('MainCtrl'/span>, function($scope, $sce) {
$scope.car = '奔馳'。
$scope.carCount = 0;
$scope.iframeSource = ""/span>;
// INIT
$scope.increaseCount = function () {
//首先等待iframe加載。
$scope.onIframeLoad = function () {
console.log('Iframe fully loaded')。
increaseCount(); // If iframe loaded then execute main INIT logic。
};
// INIT主體--主要INIT邏輯。
function increaseCount ( ) {
$scope.$apply('carCount = 10'); //將$scope.carCount改成10。
}
};
//當點擊按鈕時加載iframe。
$scope.loadIframe = function () {
console.log("Clicked on the button." )。
$scope.iframeSource = "https://www.youtube.com/embed/Ra__OWuOU1M"/span>。
}
});
<script src="https://cdnjs. cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>/span>
< div ng-app="App" ng- controller="MainCtrl" ng-init="enhanceCount()">
<h1>{{ car }}計數。{{ carCount }}</h1>
< iframe iframe-onload="onIframeLoad()" ng-src="{{ iframeSource }}" > </iframe>>
<button ng-click="loadIframe()" > 加載Iframe</button>。
</div>/span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/307478.html
標籤:
上一篇:承諾鏈的捕捉
