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?
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).
Attribute directives such as ngClass, ngStyle are modifying the DOM elements based on the renderer.
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.
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.
With version 1.1.5 you can use ng-if as @Abilash suggests:
<img ng-if="p.img" ng-src="/images/{{p.img}}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With