Passing object attributes to a modal in AngularJS

I am trying to figure out how to pass a complete object to my modal so that I can view all of its attributes there. Currently, the items I have look like this:

$scope.items = [{ Title: title, Id: id }] 

On my html page, I am using 'ng-repeat' as follows:

<tr ng-repeat="item in items | filter:search">
<td> {{item.Title}} </td>
<td> {{item.Id}} </td>
<td> <button ng-controller="ModalDemoCtrl" type="button" ng-click="viewItem(item)" class="btn btn-primary">View Item</button> </td>

And here is my modal html code:

<div class="modal-header">
  <h3>{{Title }}</h3>
</div>
<div class="modal-body">
  <p>{{ Id }}</p>
</div>
<div class="modal-footer">
  <button class="btn btn-primary" ng-click="ok()">OK</button>
  <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>

Currently, I am only able to display two values from the item.

I am struggling with how my modalController should be set up in order to pass the entire item (which currently only has a title and an ID) to the modal view.

The example on the angular bootstrap github page was followed while creating my controller:

angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {

$scope.viewItem = function () {

var modalInstance = $modal.open({
  templateUrl: 'myModalContent.html',
  controller: 'ModalInstanceCtrl',
  resolve: {
    items: function () {
      return $scope.items;
    }
  }
});

modalInstance.result.then(function (selectedItem) {
  $scope.selected = selectedItem;
}, function () {
  $log.info('Modal dismissed at: ' + new Date());
});
};

angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {

$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};

$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};

$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});

I understand that the current setup may not work as expected. I will update with my actual controller later tonight. Any suggestions on how I can achieve this would be greatly appreciated.

Answer №1

To achieve your goal, you don't have to send the entire list of items to your modal window. Instead, you only need to pass the specific item that the user has clicked on. This particular item is actually sent as an argument to your viewItem function, so your code would look something like this:

$scope.viewItem = function (selectedItem) {
  var modalInstance = $modal.open({
    templateUrl: 'myModalContent.html',
    controller: 'ModalInstanceCtrl',
    resolve: {
      item: function () {
        return selectedItem;
      }
    }
  });
}

Then, within your modal controller:

angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, item) {
  $scope.title = item.title;
  $scope.id = item.id
});

Alternatively, you can directly assign the passed item to the $scope.item variable in your modal controller and use {{item.title}} and {{item.id}} in your HTML instead.

Answer №2

In my opinion, there is no need to set up a new controller for this task; you can simply utilize your existing one. Displaying a modal window can be easily achieved by using directives like ng-show or ng-if within the same controller. It's advisable to stick with one controller per view to maintain clarity and simplicity.

If you intend to implement reusable modal windows across various sections of your project, consider creating a custom directive specifically designed for handling such scenarios within your application.

Answer №3

When defining the Items function, I suggest passing an object so that you can easily access it in your modal controller:

angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {

$scope.viewItem = function () {

var modalInstance = $modal.open({
  templateUrl: 'myModalContent.html',
  controller: 'ModalInstanceCtrl',
  resolve: {
    items: function () {
      return myItems: $scope.items;
    }
  }
});

modalInstance.result.then(function (selectedItem) {
  $scope.selected = selectedItem;
  }, function () {
  $log.info('Modal dismissed at: ' + new Date());
  });
};

angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {

$scope.items = items.myItems;
$scope.selected = {
item: $scope.items[0]
};

$scope.ok = function () {
  $modalInstance.close($scope.selected.item);
};

$scope.cancel = function () {
  $modalInstance.dismiss('cancel');
  };
});

This setup is currently functioning well in my application. Hopefully, this example is helpful to you as well.

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

Ways to remove a dynamic field with jquery

I have developed a script that allows me to add dynamic fields and delete them as needed. However, I am facing an issue where I cannot delete the first element with the "el" class in my script because it removes all elements within the "input_fields_cont ...

Utilizing pop-up alerts and AJAX requests in jQuery forms

I am looking to enhance my website by creating a form using PHP and jQuery. Currently, the form is placed in the footer of my website. However, I want to display the form results in a popup within the main section of the website without requiring a page ...

Divide a string into an array starting from the end

I have a unique phrase. var phrase = "LoremipsumdolorsitametconsectetuadipiscingelitSeddoeiusmodtemporincididuntutlaboreetaliqua"; I am interested in dividing it into chunks of 11 characters starting from the end. Currently, I use: function splitPhrase ...

What is the Proper Way to Add Inline Comments in JSX Code?

Currently, I am in the process of learning React and I have been experimenting with adding inline comments within JSX. However, when I try to use the regular JavaScript // comments, it leads to a syntax error. Let me share a snippet of my code below: const ...

How can a single item from each row be chosen by selecting the last item in the list with the radio button?

How can I ensure that only one item is selected from each row in the list when using radio buttons? <?php $i = 1; ?> @foreach ($products as $product) <tr> <td scope="row">{{ $i++ }}</td> <td>{{ ...

The issue with the max-height transition not functioning properly arises when there are dynamic changes to the max-height

document.querySelectorAll('.sidebarCategory').forEach(el =>{ el.addEventListener('click', e =>{ let sub = el.nextElementSibling if(sub.style.maxHeight){ el.classList.remove('opened&apos ...

Using AngularJs to inject a service into a controller

I'm new to AngularJs and struggling with injecting a service into a controller in AngularJS. Despite reading numerous tutorials and topics on stackoverflow, I can't seem to resolve the issue due to both the controller and service using the same m ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

"Exploring the challenges of implementing a jquerytools tooltip with AJAX

Currently, I have set up an ajax call to run every 15 seconds. The issue arises when the ajax call disables the tooltip if it's open at that moment for a particular item. This results in the destruction of only the tooltip being displayed, leaving oth ...

unable to retrieve value from JSON object

It appears that I'm having trouble accessing my object variables, most likely due to a silly mistake on my part. When I console.log my array of objects (pResult), they all look very similar with the first object expanded: [Object, Object, Object, Obj ...

Different Option for Ajax/Json Data Instead of Using Multiple Jquery Append Operations

I am working on a complex data-driven application that heavily relies on Ajax and Javascript. As the amount of data returned for certain value selections increases, the application is starting to struggle. This is more of a brainstorming session than a q ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

How to control the activation of ng-click in an Angular application

Modify the condition in ng-click so that it is clickable only if the length is greater than 1. ng-click="filtered.length > 1 ? 'false' : 'true' || showSomething($index)" What needs to be corrected here? ...

Leveraging server-side data with jQuery

When my client side JQuery receives an array of JSON called crude, I intend to access and use it in the following way: script. jQuery(function ($) { var x = 0; alert(!{JSON.stringify(crude[x])}); ...

Obtain an Array Following the For Loop

Struggling with grasping the concept of for loops in arrays. I'm attempting to develop a Thank You card generator and here are the steps I am endeavoring to execute: Initialize a new empty array to store the messages Loop through the input array, con ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

Guide to adding and showing records without the need to refresh the webpage using CodeIgniter

Hey there! I've got a code snippet here for inserting and displaying records without refreshing the web page using AJAX and plain PHP. However, I'm not sure how to set this up using CodeIgniter. Can someone please lend a hand? Here's what I ...

How can one save a text value element from a cascading list in ASP.NET MVC?

I have recently started learning about javascript, jquery, and ajax. In my model, I have defined the following classes: namespace hiophop.Models { public class CarMake { public class Category { public int CategoryID { g ...

What can we expect from the behavior of a localhost Express app with an Aurelia/Angular Admin Panel?

Currently, I am working on a Web Project that utilizes Express to serve the website and an Aurelia (or any Framework) App as an Admin Panel for editing the content. The Aurelia-App is being served through the static/public directory of Express, with the co ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...