Ng-Src-5

 

In this example of Ng-Src, We have provided a button that will change the picture randomly. Here is the function to get the image src: $scope.changeImage = function (index) { $scope.picIndex == 3 ? $scope.picIndex = 1 : $scope.picIndex += 1; $scope.picUrl = index == 1 ? "http://learnit.visrosoftware.com/datafiles/Nature-2.jpg" : (index == 2 ? "http://learnit.visrosoftware.com/datafiles/Nature-3.jpg" : "http://learnit.visrosoftware.com/datafiles/Nature-1.jpg"); };

 
 
 
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Welcome to LearnKode - A code learning platform</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> </head> <body ng-app="myApp" ng-controller="myController"> <div class="container well text-center"> <h2 class="text-primary">Change ng-src on button click</h2> <img ng-src="{{picUrl}}" height="300" width="500" /><br /><br /> <button class="btn btn-primary btn-xs" ng-click="changeImage(picIndex)">Change Picture</button> </div> <script> var app = angular.module("myApp", []); app.controller('myController', ['$scope', function ($scope) { $scope.picIndex = 1; $scope.picUrl = "http://learnit.visrosoftware.com/datafiles/Nature-1.jpg"; $scope.changeImage = function (index) { $scope.picIndex == 3 ? $scope.picIndex = 1 : $scope.picIndex += 1; $scope.picUrl = index == 1 ? "http://learnit.visrosoftware.com/datafiles/Nature-2.jpg" : (index == 2 ? "http://learnit.visrosoftware.com/datafiles/Nature-3.jpg" : "http://learnit.visrosoftware.com/datafiles/Nature-1.jpg"); }; }]); </script> </body> </html>
Output