Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 216
Max Favilli Avatar asked Mar 16 '13 15:03

Max Favilli


People also ask

What is DOM manipulation in AngularJS?

When it comes to do DOM manipulation, binding event, etc... It happens, that we define functions that manipulates the DOM in a custom directive's link function, but we call it from the controller (we define functions in the $scope so it can be accessible by the given controller).

Which directives are used to manipulate DOM elements AngularJS?

Attribute directives such as ngClass, ngStyle are modifying the DOM elements based on the renderer.

What is content DOM in angular?

The content DOM defines the innerHTML of directive elements . Conversely, the view DOM is a component's template (component.html) excluding any template HTML nested within a directive.


2 Answers

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.

like image 125
Mark Rajcok Avatar answered Oct 19 '22 12:10

Mark Rajcok


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

<img ng-if="p.img" ng-src="/images/{{p.img}}"/>
like image 29
Rob Bygrave Avatar answered Oct 19 '22 12:10

Rob Bygrave