Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  189] [ 5]  / answers: 1 / hits: 59854  / 11 Years ago, tue, july 9, 2013, 12:00:00

I've been searching for an answer to simple but not trivial question: What is a right way to catch image' onload event in Angular only with jqLite? I found this question , but I want some solution with directives.

So as I said, this is not accepted for me:



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


because it is in controller, not in directive.


More From » angularjs

 Answers
40

Here's a re-usable directive in the style of angular's inbuilt event handling directives:



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 });
});
});
}
};
}]);


When the img load event is fired the expression in the sb-load attribute is evaluated in the current scope along with the load event, passed in as $event. Here's how to use it:



HTML



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


JS



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


Note: sb is just the prefix I use for my custom directives.


[#77119] Sunday, July 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arielle

Total Points: 373
Total Questions: 105
Total Answers: 96

Location: Azerbaijan
Member since Fri, May 12, 2023
1 Year ago
;