S
S
Seva2015-09-09 14:57:21
JavaScript
Seva, 2015-09-09 14:57:21

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}}">

Function:
$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;
            }
        })
    }

ng-if doesn't wait for the image to load. How to be? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2015-09-09
@healqq

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

And in html we will have the following:
Don't forget to set isGoodSize to false when initializing the array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question