Reputation: 197
I have a directive that rescale and crop an image depending on its height and width.
angular.module('starter.directives', ['starter.controllers']).directive('styleImage', function () {
return {
restrict: 'A',
link: function preLink(scope, elem, attr) {
elem.on('load', function () {
styleImage(elem[0])
});
}
};
})
which styleImage function gets the elements width and height and rescale and crop it. And I call the directive as follow:
<img ng-src="{{user.image_path }}" class="user-image" style-image
id="{{'user'+user.user_id}}">
Everything is OK except when I load the page it takes a few second in order for the directive to rescale and crop the image. So at first the images appears with their initial width and size. Is it possible that I force the directive runs before the image is load? If so, how can I achieve it?
Upvotes: 0
Views: 163
Reputation: 4319
the sequence of events in Angular is
1- Routes
detect the URL requested via browser.
2- Http request
to get the view templateUrl declared in your routing.
3- View
rendered on the page.
4- directives
on the view firing
So it's the normal behavior to see the image then to see it cropped,
I think the solution is to use template in your directive I mean something like this
HTML
<style-image my-src='user.image_path'></style-image>
Directive
angular.module('starter.directives', ['starter.controllers']).directive('styleImage', function () {
return {
restrict: 'E',
scope{
mySrc:"="
},
link: function preLink(scope, elem, attr) {
var img= document.createElement('img');
img.setAttribute('src',scope.mySrc)
styleImage(img)
elem.append(img);
}
};
})
Upvotes: 1