Patrick Grimard
Patrick Grimard

Reputation: 7126

Prevent images from loading in an AngularJS view if scope variable is empty

Given this view markup, I'm linking to an image on the server dynamically using values in the scope. Upon first loading the page, images is empty, so the second div is displayed to say there are no images. However, since the first div contains an img tag, it attempts to download the image from the server when the view itself is downloaded by the browser. I've tried wrapping the anchor and image tag in a div with ng-if="image", but that doesn't fix it.

<div>

    <form role="form" class="search">
        <div class="input-group-lg input-group">
            <input type="text" class="form-control" placeholder="Order Number ex: 0479493" ng-model="orderNumber">
            <span class="input-group-btn">
                <button type="submit" class="btn btn-primary" ng-click="search()">Search</button>
            </span>
        </div>
    </form>

    <div ng-show="images.length > 0">
        <div class="well image-descriptor" ng-repeat="image in images">
            <p><strong class="col-sm-2">Name:</strong> {{ image.name }}</p>
            <p><strong class="col-sm-2">Index:</strong> {{ image.index }}</p>
            <p><strong class="col-sm-2">Pages:</strong>{{ image.pages.length }}</p>
            <p><strong class="col-sm-2">Path:</strong> {{ image.path }}</p>
            <p><strong class="col-sm-2">Type:</strong> {{ image.type }}</p>
            <div ng-if="image">
                <a ng-repeat="p in image.pages" href="/api/images/{{ orderNumber }}/{{ image.index }}/{{ p }}" target="_blank">
                    <img width="200" height="259" src="/api/images/{{ orderNumber }}/{{ image.index }}/{{ p }}">
                </a>
            </div>
        </div>
    </div>
    <div ng-hide="images.length > 0">
        <div class="well well-lg bg-info center-block">
            <p>No images found.</p>
        </div>
    </div>
</div>

Upvotes: 0

Views: 988

Answers (1)

V31
V31

Reputation: 7666

First you need to use ng-src and try to use ng-show on the img tag itself

<img width="200" height="259" ng-show="image" ng-src="/api/images/{{ orderNumber }}/{{ image.index }}/{{ p }}" />

Upvotes: 4

Related Questions