Created
July 10, 2024 10:42
-
-
Save olenkadark/592add8bfb53a45d9399ff9074e81cca to your computer and use it in GitHub Desktop.
Directive to show a loader until the image is ready in AngularJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('app', []) | |
.directive('onFinishRender', function ($timeout) { | |
return { | |
restrict: 'A', | |
link: function (scope, element, attr) { | |
element.attr('style', 'display:none'); // hide the image until it's loaded | |
element.on('load', function () { | |
element.attr('style', ''); | |
$timeout(function () { | |
scope.$emit('ngOnFinishRender') | |
}); | |
}); | |
} | |
} | |
}) | |
.controller('ImageController', function($scope){ | |
$scope.loading = true; // show loader initially | |
$scope.img = 'path_to_your_image.jpg'; | |
$scope.$on('ngOnFinishRender', function(ngRepeatFinishedEvent) { | |
$scope.loading = false; // hide loader once image is loaded | |
}); | |
}); | |
//==== | |
<div ng-controller="ImageController"> | |
<img ng-src="{{img}}" on-finish-render> | |
<div ng-show="loading">loading...</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment