Using ng-src and ng-href

Usually, AngularJS expressions are very flexible in that they can be used with any directive or html attributes. For eg. the title attribute can be used with an AngularJS expression like

<img title="{{ctrl.imgTitle}}">
Most AngularJS directives, on the other hand, work with direct binding from the controller’s instance or the $scope. For eg. we would use ng-show as follows:
<div ng-show="ctrl.shouldShow()"></div>
and not as
<div ng-show="{{ctrl.shouldShow()}}"></div>
 i.e. there is no need to need to use the double curly brackets {{}} while using most angular directives. But there are two special AngularJS directives, viz. ng-src and ng-href which must be used with the {{}}.

Need for ng-src and ng-href

The html src and href attributes can actually work with AngularJS expressions like <img src=”{{imgUrl}}”> or <a href=”{{nextLink}}”>. But the catch here is that, Angular requires some time to load initially. This means that the $scope or the controller may not have been initialized and hence both the variables in the above examples, viz. imgUrl and nextLink are undefined. This could lead to img tag throwing an error with no image. What ng-src and ng-href do is that they wait for AngularJS to load before before filling up their respective values. This makes sure that no null image request is sent or empty link displayed. Even before Angular loads the browser will use the content of the src tag to fetch the image from the server. This will also be prevented by using ng-src.

Only use ng-src and ng-href if you have dynamic links or have to load images dynamically. Use the href and src otherwise.

Need for {{}} while using ng-src and ng-href

Most AngularJS directives expect an expression as their value, so using {{}} is not required as there is direct binding using $scope. But ng-href and ng-src are special in that they require interpolation expressions as values rather an object, to make it’s functionality as close to the html src and href tags as possible. Thus, the proper way to use ng-src and ng-href would be:

<a ng-href="{{ctrl.pageLink}}"></a>
and
<img ng-src="{{ctrl.imgUrl}}">

This post is also available on abhiroop.com

Abhiroop PatelUsing ng-src and ng-href