- AngularJS provides ngSrcset attribute directive for handling multiple images based on condition.
- It is really helpful for handling responsive images.We can use this directive for showing different images based on screen width.
- In this demo,"We will use Gravatar images of different size for for different screen size".
- Below code shows the use of ngSrcset with a set of images and conditions. To see the ngSrcset in action try to resize your windlow.
<!DOCTYPE html> <html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>AngularJS ngSrcset Example</title>
</head>
<body ng-controller="MyController">
<h3>ngSrcset directive Example</h3>
<img ng-srcset="{{myImageSize100}},{{myImageSize100}},{{myImageSize200}}"></img>
<script>
var myApp = angular.module("myApp", []);
myApp.controller("MyController", ["$scope", function($scope) {
$scope.myImageSize50 = "http://www.gravatar.com/avatar/c6e6c57a2173fcbf2afdd5fe6786e92f.png?s=50 100w";
$scope.myImageSize100 = "http://www.gravatar.com/avatar/c6e6c57a2173fcbf2afdd5fe6786e92f.png?s=100 300w";
$scope.myImageSize200 = "http://www.gravatar.com/avatar/c6e6c57a2173fcbf2afdd5fe6786e92f.png?s=200 700w";
}]);
</script>
</body>
</html>
- The output of the above code is embedded in below JSBIN link.Just resize the window to check how ngSrcset changes the image URL and display different Gravatar image size.