Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

AngularJS Tip - Avoid Multiple Variables in ng-src

DZone's Guide to

AngularJS Tip - Avoid Multiple Variables in ng-src

· Java Zone
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

Before I start, let me be clear I'm still learning AngularJS and this "tip" may be 100% wrong. I just ran into this with an application and most likely there is a better way to address what I did.

In the application I'm building, I've got a detail page that displays an image. The site uses an image folder that uses a subdirectory for the size of the image, so for example, the base image folder is: foo.com/products/images. For the thumbnail of product X, the image would be: foo.com/products/images/thumbs/x.jpg. For the larger size, it would be: foo.com/products/images/large/x.jpg.

To make things simpler, I used a partial that looked like this.

<img ng-src="{{imageroot}}/{{product.image}}">

For folks who don't know Angular, the ng-src directive ensures that when the partial is loaded, the browser doesn't try to load an invalid image. If I had used src="...", there would be two network requests - first for the tokenized version of the URL and then for the real value.

I thought this was working fine, but I then noticed something odd in my network tools - a request for foo.com/products/images/thumbs. From what I can see, it looks like Angular sets the src of the image element as soon as it is able to replace one of the tokens.

To fix this, I simply edited the template to use one variable and I set that value properly in my controller.

<img ng-src="{{image}}">

The controller code:

$scope.product = data;
$scope.image = IMG_URL + "thumbs/" + data.image;


Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}