Tutorial #12: Angular JS – How to Hide/Show Pictures

Posted by


In this tutorial, we will learn how to use AngularJS to hide and show pictures based on user interaction. This functionality can be useful in many scenarios, such as creating image galleries, product listings, or interactive user interfaces.

Before we begin, make sure you have a basic understanding of AngularJS and have it set up in your project. If you are new to AngularJS, I recommend checking out some introductory tutorials before diving into this one.

Step 1: Set up your project
First, create a new AngularJS project or open an existing one. Make sure you have included the AngularJS library in your project. You can do this by adding the following line in the section of your HTML file:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

Step 2: Create an image gallery
Next, we will create a simple image gallery using AngularJS. For this tutorial, we will use a list of image URLs stored in an array. You can replace these URLs with your own images later.

<div ng-app="myApp" ng-controller="myCtrl">
  <img ng-src="{{currentImage}}" ng-click="toggleImage()">
</div>

In the JavaScript code, define the AngularJS app and controller like this:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.images = [
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg',
    'https://example.com/image3.jpg'
  ];

  $scope.currentIndex = 0;
  $scope.currentImage = $scope.images[$scope.currentIndex];

  $scope.toggleImage = function() {
    $scope.currentIndex = ($scope.currentIndex + 1) % $scope.images.length;
    $scope.currentImage = $scope.images[$scope.currentIndex];
  };
});

Step 3: Hide and show the picture
Now that we have set up our image gallery, we can add functionality to hide and show the picture based on user interaction. We will use AngularJS directives for this purpose.

<div ng-app="myApp" ng-controller="myCtrl">
  <button ng-click="toggleImage()">Toggle Image</button>
  <img ng-src="{{ currentImage }}" ng-hide="isImageHidden">
</div>

In the JavaScript code, add a variable to keep track of whether the image is hidden or not:

$scope.isImageHidden = false;

$scope.toggleImage = function() {
  $scope.isImageHidden = !$scope.isImageHidden;
};

Now, clicking the "Toggle Image" button will hide or show the image in the gallery.

Step 4: Further customization
You can further customize the functionality by adding animations, transitions, or other effects when hiding and showing the image. You can also use ng-if or ng-switch directives to achieve similar functionality.

I hope this tutorial has helped you understand how to use AngularJS to hide and show pictures in your web applications. You can now apply this knowledge to create more interactive and dynamic user interfaces. Thank you for reading!