[英]AngularJS - Image “onload” event
我一直在尋找一個簡單但並非瑣碎的問題的答案:僅使用jqLite在Angular中捕獲圖像的onload
事件的正確方法是什么? 我找到了這個問題 ,但是我想要一些指令解決方案。
因此,正如我所說,這對我來說是不可接受的:
.controller("MyCtrl", function($scope){
// ...
img.onload = function () {
// ...
}
因為它在控制器中,而不在指令中。
這是angular內置事件處理指令樣式的可重用指令:
angular.module('sbLoad', [])
.directive('sbLoad', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var fn = $parse(attrs.sbLoad);
elem.on('load', function (event) {
scope.$apply(function() {
fn(scope, { $event: event });
});
});
}
};
}]);
觸發img load事件時,將在當前作用域中將sb-load屬性中的表達式與load事件一起評估,並作為$ event傳入。 使用方法如下:
的HTML
<div ng-controller="MyCtrl">
<img sb-load="onImgLoad($event)">
</div>
JS
.controller("MyCtrl", function($scope){
// ...
$scope.onImgLoad = function (event) {
// ...
}
注意:“ sb”只是我用於自定義指令的前綴。
好的,jqLite的bind
方法表現出色。 它是這樣的:
我們在img
標簽中添加指令名稱作為屬性。 就我而言,圖像加載后並根據其尺寸,必須將其類名稱從“水平”更改為“垂直”,因此指令的名稱將是“可定向的”:
<img ng-src="image_path.jpg" class="horizontal" orientable />
然后我們創建如下的簡單指令:
var app = angular.module('myApp',[]);
app.directive('orientable', function () {
return {
link: function(scope, element, attrs) {
element.bind("load" , function(e){
// success, "onload" catched
// now we can do specific stuff:
if(this.naturalHeight > this.naturalWidth){
this.className = "vertical";
}
});
}
}
});
示例(顯式圖形!): http : //jsfiddle.net/5nZYZ/63/
AngularJS V1.7.3添加了ng-on-xxx
指令:
<div ng-controller="MyCtrl">
<img ng-on-load="onImgLoad($event)">
</div>
AngularJS為許多事件(例如ngClick
提供了特定的指令,因此在大多數情況下,沒有必要使用ngOn
。 但是,AngularJS並不支持所有事件,以后的DOM標准中可能會引入新的事件。
有關更多信息,請參閱《 AngularJS ng-on指令API參考》 。
您可以在angular js中調用onload事件的javascript版本。 此ng-load事件可以應用於任何dom元素,例如div,span,body,iframe,img等。以下是在現有項目中添加ng-load的鏈接。
npm i angular-ng-load
以下是iframe的示例,加載后將在控制器中調用testCallbackFunction
例
JS
// include the `ngLoad` module
var app = angular.module('myApp', ['ngLoad']);
app.controller('myCtrl', function($scope) {
$scope.testCallbackFunction = function() {
//TODO : Things to do once Element is loaded
};
});
的HTML
<div ng-app='myApp' ng-controller='myCtrl'>
<iframe src="test.html" ng-load callback="testCallbackFunction()">
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.