Obtaining images from JSON data and displaying them in a modal using AngularJS

Utilizing AngularJS to retrieve a JSON file:

{
 "albumId": 1,
 "id": 1,
 "title": "accusamus beatae ad facilis cum similique qui sunt",
 "url": "http://placehold.it/600/92c952",
 "thumbnailUrl": "http://placehold.it/150/92c952"
},

and showcasing it with ng-repeat:

<div ng-repeat="image in images" class="col-xs-2 ">
   <div class="thumbnail">
      <img src="{{ image.thumbnailUrl }}" alt="" ng-click="open()" />

   </div>
</div>

Everything is functioning smoothly. Next, I integrated ui.bootstrap to connect the thumbnails and trigger a modal window opening.

controller:

    app.controller("page3Ctrl",['$scope', '$resource', '$uibModal', function ($scope, $resource,$uibModal) {

    var postingsResource = $resource('http://jsonplaceholder.typicode.com/photos', {});
    $scope.images = postingsResource.query();


    $scope.open = function() {
        var uibModalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'modal.html'

        });
    };

}]);

Everything is working well. Now, the question arises - how can I dynamically display the corresponding image from thumbnailUrl in the modal URL? They need to match up.

Answer №1

If you're not utilizing a controller for the modal feature, you can simply set $scope as the scope for the modal and assign the selected image to a scope variable to access it in the modal template.

var app = angular.module('app', ['ngResource','ui.bootstrap']);
app.run(function($templateCache){
  $templateCache.put('modal.html', '<div><a ng-click="$close(true)" class="pull-right">&times close</a><img ng-src="{{currentImage.url}}"/></div>');
});
app.controller("page3Ctrl", ['$scope', '$resource', '$uibModal', function($scope, $resource, $uibModal) {

  var postingsResource = $resource('http://jsonplaceholder.typicode.com/photos', {});
  $scope.images = postingsResource.query();

 //no controller for modal
  $scope.open = function(image) {
    $scope.currentImage = image;
    var uibModalInstance = $uibModal.open({
      animation: true,
      scope:$scope,
      templateUrl: 'modal.html'
    });
  };
  
  /*
  //modal has controller
  $scope.open = function(image) {
    var uibModalInstance = $uibModal.open({
      animation: true,
      templateUrl: 'modal.html',
      resolve: {
        image: function(){
          return image;
        }
      },
      controller: function($scope, image){
        $scope.currentImage = image;
      }
    });
  };
  */

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.5.11/angular-resource.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<div ng-app="app" ng-controller="page3Ctrl">
  <div ng-repeat="image in images.slice(0,10)" class="col-xs-2 ">
    <div class="thumbnail" ng-click="open(image)">
      <img ng-src="{{ image.thumbnailUrl }}" alt="" ng-click="open()" />

    </div>
  </div>
</div>

Answer №2

To enhance the open function, consider including an argument that takes in the image's URL. Here's how you can do it:

$scope.open = function(imageUrl) {
    var uibModalInstance = $uibModal.open({
        animation: true,
        templateUrl: 'modal.html',
        controller: ModalInstanceCtrl,
        resolve: {
           imageUrl: function () {
             return imageUrl;
           }
        }
    });
}

Now, implement this in your HTML by passing the image URL when clicking on the thumbnail:

<img src="{{ image.thumbnailUrl }}" alt="" ng-click="open(image.url)" />

Remember to pass this parameter to the modal controller as well:

var ModalInstanceCtrl = function ($scope, $modalInstance, imageUrl) {
    $scope.imageUrl = imageUrl;
};

For more information on passing values to a modal controller, check out this resource: Pass parameter to modal

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The execution of Node.js on data is triggered only after the content has been successfully written

Hello, I am attempting to establish a connection to a telnet server using Node's net library. const net = require('net'); const con = new net.Socket(); con.connect(23,'10.0.0.120', () => { console.log('Telnet connected ...

How to Retrieve the Number of Requests in an Express Application

Is there a method to retrieve the overall count of requests in a specific route using Expressjs? ...

Angular and Bootstrap 5 combine to create a dynamic multi-item carousel featuring animated slide transitions and embedded YouTube videos

I'm trying to create a multi-item carousel using YouTube videos, and although I have managed to get it working with Bootstrap 5 carousel and cards, the animation when the carousel slides is not as smooth as I would like. The issue seems to be that the ...

Next.js encountered a Runtime Error: Trying to access properties of undefined (specifically 'status') and failing

For those interested in viewing the code, it can be found here During the creation of a portfolio website using Next.js, I encountered an error. I am utilizing the latest version of Next.js (next 13.4.16) and incorporating the app router into my project. ...

Ensure that confirmation is only prompted in ASP.NET when necessary

I am faced with a scenario where I need to handle the value of Session["actionMode"] in conjunction with a button click event. Here is what I currently have implemented in my code: protected void Button1_Click(object sender, EventArgs e) { if ((int)S ...

Frequently refreshing a page to display the most recent information without needing to reload the entire

I am seeking a solution for updating the comments section on my website live or every 30 seconds. The comments are fetched from a MySQL database using PHP: <?php $link = mysql_connect('localhost', 'root', ''); ...

(React) Error: Unable to access property 'this' as it is set to undefined while trying to utilize refs

When using a ref in React to refer to an input field, I encountered an error: "Uncaught TypeError: Cannot read property 'this' of undefined". Despite having defined the ref, React seems unable to locate it in my code. What could be causing this i ...

How to handle redirects based on status codes in AngularJS $http requests

My angular application includes numerous $http requests, and I am looking for a way to automatically redirect users to the login page in case the server session expires (resulting in a 401 error). Does anyone have a solution that can handle this for all ...

Increasing the date field value in Mongoose, ExpressJS, and AngularJS with additional days

I encountered an issue while attempting to extend the number of days for an existing Date field in mongoose. Despite no errors being displayed in the browser or console, something seems to be amiss. Can anyone identify the problem in this code snippet? ...

How can you utilize data captured through a JavaScript onchange event in conjunction with another event?

Is there a way to utilize the firmType data captured during event 1 in event 2? code event 1 $("body").on("change","#so_customer", function(v){ customerFirm = $(this).find(":selected").data("employer"); $("#customer_employer").val(cust ...

Transfer the script from package.json to an npm package

In each of our plugins' root directories, there is a file named tools.js. This file contains a build function that assists in creating builds for the plugin. The package.json file references it like this: "scripts": { "build:node&qu ...

"Is there a way to retrieve "Lorem ipsum" information from a web service in JSON format

Does anyone know of any sample web services that serve JSON data? I'm looking to practice consuming JSON for testing and learning purposes. I would even be interested in downloading JSON files with images and other content to study offline. Perhaps th ...

Error: The $injector:modulerr error is occurring on the server, even though it works fine locally

I'm encountering an issue with my code when it's hosted on a server. After switching to unminified JS, I get the following error: angular.js:66 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: ReferenceError: sha ...

Error Alert: Vue is not recognized in Browserify environment

My venture into front-end development has just begun and I am experimenting with Vue.js along with Browserify. The main 'app.js' file includes: window.$ = window.jQuery = require('jquery'); require('bootstrap'); var moment = ...

Displaying a table in Chrome/Firefox with a mouseover feature

Hovering over the rows of this table triggers a display of descriptions. html: <tr title="{{transaction.submissionLog}}" class="mastertooltip">... JavaScript: $('.masterTooltip').hover(function(){ // Hover functionality ...

Retrieve Static Property Values Using jQuery/JavaScript in Backend Code

My challenge is to fetch the Max value and Percent value into a jQuery function. I attempted to retrieve these values using hidden variables and Session variables on page load, but they always return 0. Here are the properties: public static int Max { ...

The MUI makeStyles() class has been implemented, yet the styles are not being displayed when using classList.add('class-name')

Currently, I am utilizing MUI makeStyles() to create a series of CSS classes. Within these classes, I am dynamically including and excluding one specific class to my Box element during file drag-and-drop events. The class is successfully added, as I can o ...

A guide to incorporating border radius to images within a composite image with sharp.js in Node.js

In my Node.js project, I am using the sharp library to combine a collection of images into a single image. Although I have successfully created the composite image, I now need to add a border radius to each of the images in the grid. Here is the code snip ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

Is there a way to showcase all the information in products while also organizing it in the same manner that I have?

I am looking to sort prices while displaying all the properties of products at the same time. DATA INPUT: const products = [ { "index": 0, "isSale": true, "isExclusive": false, "price": "Rs.2000", "productImage": "product-1.jpg", ...