ItSolutionStuff.com

AngularJS Dynamically Change Image SRC on Click Example

By Hardik Savani • October 20, 2023
Angular

In this example, i want to show you how to change image src dynamically on image or button click event in angularjs. you will learn dynamically change the src attribute of image element when clicked using the ng-src directive in angular js.

Here, i will give you one example to change dynamic image ng-src. we will create one json array and change dynamically image when user will click on image.

So, let's see bellow code for change image on click in angular js.

index.html

<html>

<head>

<title>Angularjs dynamically change image src on click - ItSolutionStuff.com</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>

</head>

<body>

<div ng-app="MyApp" ng-controller="MyController">

<img ng-src="{{Image.Photo}}" ng-click="ImageClick()" style="height: 200px; width: 300px;

cursor: pointer" />

<p>Click on Image</p>

</div>

</body>

<script type="text/javascript">

var app = angular.module('MyApp', []);

app.controller('MyController', function ($scope, $interval) {

$scope.Images = [

{ Id: 1, Photo: "http://itsolutionstuff.com/upload/guzzle-http-request-laravel-5-8-min.jpg" },

{ Id: 2, Photo: "http://itsolutionstuff.com/upload/admin-panel-laravel-5-8-min.png" },

{ Id: 3, Photo: "http://itsolutionstuff.com/upload/ajax-form-validation-laravel-5-8.jpg" },

{ Id: 4, Photo: "http://itsolutionstuff.com/upload/rest-api-laravel-5-8.jpg" }

];

$scope.Image = $scope.Images[0];

var index = 1;

$scope.ImageClick = function () {

$scope.Image = $scope.Images[index];

index++;

if (index > $scope.Images.length - 1) {

index = 0

}

};

});

</script>

</html>

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

AngularJS - How to Create Read More/Less Toggle using Directive?

Read Now →

AngularJS Nl2br Filter for Textarea Content Example

Read Now →

How to Call AngularJS Controller Function in JQuery?

Read Now →

AngularJS Image Upload with Preview Example

Read Now →

How to Hide Div After Some Time in AngularJS?

Read Now →

AngularJS Tooltip using UI Bootstrap tpls HTML Example

Read Now →

AngularJS Simple Datepicker Directive Example Tutorial

Read Now →

AngularJS Sorting(using Orderby Filter) Table Data Example

Read Now →

How to Change Date Format using Date Filter in AngularJS?

Read Now →

AngularJS - How to Limit String Length using Filter?

Read Now →

AngularJS - How to Capitalize the First Letter of Word Example

Read Now →

How to Remove HTML Tags from String in AngularJS?

Read Now →

PHP AngularJS CRUD with Search and Pagination Tutorial

Read Now →

Codeigniter Angularjs http post not working

Read Now →