Max Favilli
Max Favilli

Reputation: 6459

How to really prevent an element from being put into the DOM with angularjs

Let's say you have the following code to display some products images:

<ul>
  <li ng-repeat="p in products">
    <img ng-src="/images/{{p.img}}"/>
  </li>
</ul>

Now let's say some products unfortunately don't have images, you may fix that with:

<ul>
  <li ng-repeat="p in products">
    <img ng-hide="p.img==undefined" ng-src="/images/{{p.img}}"/>
  </li>
</ul>

Now go to the "network" tab of firebug or chrome developer tools and check for the images download -- you will see errors, because the browser still tried to download the non-existent image. It's hidden and the users won't notice, but of course it's bad: bad practice, bad for server performance, bad bad bad...

What is the correct "angular" solution for this?

Upvotes: 6

Views: 2473

Answers (3)

Mark Rajcok
Mark Rajcok

Reputation: 364747

An alternative to @Arun's solution is to use ng-switch or ng-if (available in v1.1.5), which add/remove DOM elements, unlike ng-hide/ng-show:

<ul>
  <li ng-repeat="p in products">
    <span ng-switch="p.img==undefined">
      <img ng-switch-when="false" ng-src="/images/{{p.img}}"/>
    </span>
  </li>
</ul>

See @Rob's answer for an example using ng-if.

Upvotes: 4

Rob Bygrave
Rob Bygrave

Reputation: 4051

With version 1.1.5 you can use ng-if as @Abilash suggests:

<img ng-if="p.img" ng-src="/images/{{p.img}}"/>

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388446

You can do something like

<ul>
    <li ng-repeat="p in products | imgsrc">
        {{p.img}}
        <img ng-src="/images/{{p.img}}"/>
    </li>
</ul>


app.filter('imgsrc', function(){
    return function(data){
        var a = [];
        angular.forEach(data, function(v, i){
            if(v.img){
                a.push(v);
            }
        });
        return a;
    }
});

Demo: Fiddle

Upvotes: 1

Related Questions