Reputation: 4539
I need the dimensions of an image loaded from the web (dynamically) to adapt my display. So I need to use an onload event in the controller (the view is not rendered yet), like so :
.controller("MyCtrl", function($scope){
img.onload = function () {
// $scope changes not effective
}
I know I could use $apply
, but I'm not a huge fan of it since it hurts performances. Do you have any other solution I could use, whether for Angular to be aware of what I'm doing (which is not the case with img.onload
) or for the scope to take my changes into account?
Thanks!
Upvotes: 0
Views: 1378
Reputation: 4568
You need to use a directive
to fetch the image properties, and assign them to your scope in the controller. Here is some pseudo-code, can't guarantee it'll 100% work out of the box, but it should give you an idea on what needs to happen.
Template
<div ng-controller="MyCtrl">
<img img-size src="..." />
</div>
Directive
.directive('imgSize', function() {
return {
link: function (scope, elem, attrs) {
elem.on('load', function(e) {
var width = $(this).width();
var height: $(this).height();
scope.$evalAsync(function() {
scope.imageWidth = width;
scope.imageHeight = height;
});
});
}
}
});
Upvotes: 1
Reputation: 2509
I assume you have your image in the current View. You could access it with something like:
var elImage = document.getElementById("[your_imageId]")
After that
elImage .addEventListener('load', function() { /* ... */ }, false);
should get you further.
Upvotes: 0
Reputation: 1361
Use a directive that will inject the height/width in the the controller $scope.
<img height-width />
Upvotes: 0