Answer the question
In order to leave comments, you need to log in
How to use ng-if with async function?
The bottom line: in the template we display a picture, but only if it has the right proportions.
<img class="main-img" ng-if="showImage($index)" ng-src="{{item.img}}">
$scope.showImage = function(index) {
var img = new Image();
img.src = $scope.items[index].img;
img.addEventListener("load", function() {
var ratio = this.naturalWidth / this.naturalHeight;
if (ratio > 2) {
return true;
} else {
return false;
}
})
}
Answer the question
In order to leave comments, you need to log in
Your code is not doing what you expect.
The showImage function does not return anything (undefined), a function that returns true if the size is correct is called asynchronously and a true/false value is returned to the caller of this function.
In order for everything to work on the load event, you need to set some value. It looks like you're using ng-repeat - so a simple option would be to just set the array element 's isGoodSize flag to true when your event fires.
img.addEventListener("load", function() {
var ratio = this.naturalWidth / this.naturalHeight;
if (ratio > 2) {
$scope.items[index].isGoodSize = true;
} else {
$scope.items[index].isGoodSize = false;
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question