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

Failure of default option to appear in dropdown menu in Angular

I currently have a dropdown list in my HTML setup like this: <select id="universitySel" ng-model="universityValue" ng-options="university._id for university in universities"> <option value="-1">Choose university</option> ...

Changing the Position of HTML Scripts in React

I am facing an issue where I need to relocate an external script within a specific section of my page. However, I am unable to access the CSS attributes associated with this item. It seems that it is displayed as an iFrame, making it difficult to modify th ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

Customizing the "added to cart" message in Woocommerce and setting up a notification system for customers

My main focus is on customizing the Woocommerce notation system for a personalized shopping cart experience. After some research, I stumbled upon a very helpful user response which suggested modifying the message by adding the following code snippet to th ...

Localizing HTML number input values is not functioning properly

When using an HTML number field, I encountered the following error: The specified value "101,5" is not a valid number. The value must match the regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)? I am trying to co ...

Array Filtering Results in an Empty Array of Objects

I'm currently attempting to filter out all objects from the projects array that do not appear in the savedProjects array, but I'm ending up with an empty result. Could it be that I am approaching the filtering process incorrectly? Here's my ...

Guide on incorporating text input areas into specific positions within a string

Looking for a way to replace specific words in a string with input fields to enter actual values? For example... Dear Mr. [Father_name], your son/daughter [name] did not attend class today. This is what I want it to look like... Dear Mr. Shankar, your ...

How can I execute a StoredProcedure using JavaScript?

I have a form with an email field and label <asp:TableRow runat="server"> <asp:TableCell runat="server"> <asp:TextBox runat="server" ID="txtUserEmail" onfocusout="emailVerification()" CssClass="forTe ...

Failed to insert a new element into the MongoDB array

After trying the code below to update a document within a collection, I encountered an issue where a new item was not being added to an array in the script. Despite no exceptions being thrown, the array remained unchanged. I am seeking advice from experts ...

What is the method to store and retrieve data attributes linked to elements such as select options within the React framework?

Despite my efforts, I'm currently unable to retrieve the data attribute from an option using React as it keeps returning null. <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}> <opti ...

Delaying Variable Assignment in Node.js until Callback Function Completes

I am currently working with Node.js, Express, MongoDB, and Mongoose in my project. One specific task involves fetching the largest id number of a document from the MongoDB database and passing it back to the program. To better organize my code, I moved thi ...

The Req.session array is limited to storing just one element at a time

I'm currently working on integrating a shopping cart feature into my Express/MongoDB e-commerce app that sells sneakers. To add an item to the cart, I extract the quantity and size from req.body and the itemId from req.session (previously saved when l ...

Using Sweetalert2 to send data via AJAX POST request

Recently, I've been incorporating SweetAlert2 into my project and I want to create an "Add Note" feature. The process involves the user clicking a button, being directed to a page, and then the following script is executed: <script>swal({ ...

Toggle on and off using a checkbox feature in conjunction with the straightforward form gem

Seeking assistance in toggling an action using a checkbox on a post form. Not well-versed in javascript or JQuery. Struggling with this task while working alone. If anyone can provide guidance, it would be greatly appreciated! Using Rails 4.2.8 an ...

How can I design unique navigation menus using HTML, CSS, JavaScript, and jQuery?

Is there a way to create menus where clicking on a holiday/seasonal category opens up all related lists automatically? For example: https://i.sstatic.net/Nctd1.png I've been searching online for submenu options but haven't found the right metho ...

What is the best way to include attributes in an HTML element?

I've been researching how to dynamically add attributes to an HTML tag using jQuery. Consider the following initial HTML code: <input type="text" name="j_username" id="j_username" autocorrect="off" autocapitalize="off" style="background-image: lin ...

Mastering Data Transfer in jQuery: A Guide to Migrating Event Information from .on(dragstart) to

I need help with transferring information between an .on(dragstart) event and an .on(drop) event. However, when I run the code below in Chrome, I encounter an error message: 'Uncaught TypeError: Cannot read property 'test' of undefined' ...

Mist Conceals Celestial View (THREE.JS R76)

I have a cylindrical camera setup with fog to hide the end of the tube. However, I am trying to make the skybox visible through the alpha map sides of the cylinder. The current issue is that the fog is blocking the visibility and I'm looking for a sol ...

Sorting through items based on their characteristics, not just their numerical properties

I have JSON objects displayed on the page using ng-repeat. While I am able to search through them, I also need to be able to 'filter' them based on a specific parameter using a select HTML element. For better clarity, let's consider the fol ...

I am puzzled by this error in Typescript: "Why does the element have an 'any' type when the Object type lacks an index signature?"

Looking to extract an array of keys from an object with nested properties, my current code: public static getKeys(obj: Object) { let keys: string[] = []; for (let k in obj) { if (typeof obj[k] == "Object" && obj[k] !== null) { ...