2013-07-09 59 views
27

我一直在尋找一個簡單但不平凡的問題的答案:什麼是正確的方式來捕捉圖像'onload事件Angular只有jqLit​​e?我發現this question,但我想要一些解決指令。
因此,正如我所說,這是不能接受的對我來說:AngularJS - 圖像「onload」事件

.controller("MyCtrl", function($scope){ 
    // ... 
    img.onload = function() { 
     // ... 
    } 

,因爲它是在控制器,而不是指令。

回答

28

下面是角的內置事件處理指令的樣式可重複使用的指令:

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屬性中的表達式會在當前作用域中與作爲$ event傳入的load事件一起計算。以下是如何使用它:

HTML

<div ng-controller="MyCtrl"> 
    <img sb-load="onImgLoad($event)"> 
</div> 

JS

.controller("MyCtrl", function($scope){ 
    // ... 
    $scope.onImgLoad = function (event) { 
     // ... 
    } 

注: 「SB」 僅僅是我用我的自定義指令的前綴。

+6

謝謝山姆,這工作像一個魅力,我想我會留下sb前綴給你信用。 – Michiel

+0

贊成可擴展解決方案,無需使用jqLit​​e(從Angular 2中刪除) –

31

好的,jqLit​​e'bind方法做得很好。它是這樣的:

我們在我們的img標記中添加了指令'name as attribute「。在我的情況下,加載後,並根據其尺寸,圖像必須從「橫」向「垂直」更改它的類名,所以指令的名稱將是「定向」:

<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/