Episode 15 of 25
The ng-src Directive
Learn why ng-src is needed for dynamic image sources instead of regular src.
The ng-src directive is used to dynamically set image sources. You should never use {{ }} expressions inside a regular src attribute.
The Problem with Regular src
<!-- BAD — browser makes a request to "{{ user.avatar }}" literally -->
<img src="{{ user.avatar }}" alt="Avatar">
<!-- GOOD — AngularJS handles the binding correctly -->
<img ng-src="{{ user.avatar }}" alt="Avatar">
Why ng-src?
The browser processes HTML before AngularJS. It sees src="{{ user.avatar }}" and tries to load an image from the literal URL {{ user.avatar }}, which fails. ng-src waits for AngularJS to evaluate the expression first.
Practical Examples
app.controller('GalleryCtrl', function($scope) {
$scope.images = [
{ url: 'img/photo1.jpg', title: 'Sunset' },
{ url: 'img/photo2.jpg', title: 'Mountain' },
{ url: 'img/photo3.jpg', title: 'Ocean' }
];
$scope.selected = $scope.images[0];
$scope.selectImage = function(img) {
$scope.selected = img;
};
});
<div ng-controller="GalleryCtrl">
<img ng-src="{{ selected.url }}" alt="{{ selected.title }}">
<h3>{{ selected.title }}</h3>
<div ng-repeat="img in images">
<img ng-src="{{ img.url }}" ng-click="selectImage(img)"
alt="{{ img.title }}" class="thumbnail">
</div>
</div>
Other ng- Attribute Directives
<a ng-href="{{ dynamicUrl }}">Link</a>
<div ng-style="{ color: myColor }">Styled</div>
<div ng-class="{ active: isActive }">Classed</div>