Transferring information between controllers within a uib modal window

I have created a custom uib modal in my angularjs application. The body and footer content of the modal need to change based on certain conditions so I have implemented it this way for now. Everything seems to be functioning correctly, but I want to ensure that I am following best practices...

When a button inside the modal is clicked, I am checking the text of the clicked button. I do not want the modal to be treated as a directive.

HTML snippet

<div class="modal-header" >
   <button type="button" class="close" ng-click="close()" data-dismiss="modal">&times;</button>
   <h4><b>{{customModal.title}}</b></h4>
</div>
<div class="modal-body">
 {{customModal.body}}
</div>
<div class="modal-footer" >  
   <span ng-repeat="item in customModal.buttons">
   <button type="button" class="{{item.btnClass}}" ng-click="modalBtnClick(customModal,item);close()" data-dismiss="modal" ng-if="item.show">{{item.text}}</button>
   <span>
</div>

Invoke the modal upon clicking.....

$scope.areYouSureModalInstance = $uibModal.open({
  animation: true,
  templateUrl: 'views/Modal.html',
  controller: 'ModalCtrl',
  windowClass: 'nested-modal',
  scope: $scope,
  resolve: {
    items: function() {
      let btns=[
          {id:1,text:"Yes",show:true, btnClass:"btn btn-success"},
          {id:2,text:"No",show:true, btnClass:"btn btn-danger"},
          {id:3,text:"Cancel",show:true, btnClass:"btn btn-default"}
        ];
      $scope.customModal = {
        id:'confirm',
        title:'Confirm',
        body:'Do you want to save the changes you have made?',
        buttons:btns
      };
      //passing the modal properties
      return $scope.customModal;
    }
  }
});

 //Inside the uib modal controller

   function ModalCtrl($scope) {

    $scope.close = function() {
      $scope.areYouSureModalInstance.close();
    };

     $scope.modalBtnClick=function(data,btn){
      if(data.id==="confirm"){
       $scope.$emit('close.confirm',btn);
      }
   };
 }


//When a user clicks on any button


$scope.$on('close.confirm', function(event, data) {

if (data.text.toLowerCase()==="no") {
  //perform some actions here
 }
if (data.text.toLowerCase()==="yes") {
  //perform some actions here
}
$scope.modalInstance.close();
});

Is there a more efficient approach to achieve this with two controllers without using the modal as a directive?

Answer №1

In AngularJS $uibModal.open().result
will give you a Promise.

Therefore, to handle the promise result, you can subscribe like this:

$scope.confirmationModalInstance.then(function(response) {
  //handle the arguments returned by the modal
  console.log(response);
}, function (error) {
  //handle any errors here
});

This code snippet is for handling the closing and confirmation method of the modal

function ModalController($scope, $uibModalInstance) {

 $scope.closeModal = function() {
   $uibModalInstance.dismiss();
 };

 $scope.handleModalButtonClick = function(data, button){
  if(data.id === "confirm"){
   // button -> arguments passed to the modal
   $uibModalInstance.close(button);
  }
 };
}

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

Various conditional statements based on the dropdown menu choice

I currently have a basic dropdown menu on my webpage that enables users to switch between viewing Actual or Planned dates/times in a table (I am utilizing the controller as syntax): <select ng-model="trip.viewType"> <option value="actual"> ...

Guide on creating a custom directive called 'ng-let' to associate an expression with a variable

If I want to create a custom directive that functions like ng-repeat but assigns a name to a single variable: instead of writing code like this: ng-repeat="summary in data.accounts.all.summaryAsArray()" I could write something similar to this: ng-let=" ...

What is the best way to incorporate AngularJS data into JavaScript for use in Google Chart?

How can I leverage my AngularJS scope data in a Google Chart or JavaScript? Below is my AngularJS file: angular.module('reports').controller('ReportInfoCtrl', ['$scope', 'reports', '$rootScope','$loca ...

Issue with Angular UI-Grid: Tooltip not appearing

I'm having trouble implementing a filter on ui-grid cells while also adding a tooltip. The filter works fine, but the tooltip does not display unless I remove the filter. cellFilter: 'number: 2', cellTooltip: 'Custom tooltip - maybe som ...

imported classes from a module cannot be accessed within the same module

Here is some TypeScript code that I wrote: Within my module, I am importing a library called ts-events. import {SyncEvent} from 'ts-events' module MyModule{ export class MyService{ } } In the same module but in a different file, I'm ...

Is it possible to dynamically add elements in AngularJS without relying on directives?

As a newcomer to Angularjs and not very fluent in English, I embarked on the journey of adding <li> using directives. You can see the result of my first attempt at this link. Next on my list was mastering two-way binding by passing values between th ...

How to inject a variable into an AngularJS service that utilizes both $http and $interval functions?

Struggling with $http and $interval, I stumbled upon this code. http://embed.plnkr.co/fSIm8B/script.js I forked it here: http://plnkr.co/edit/Al8veEgvESYA0rhKLn1q To make it more functional, how can I pass a variable to the service? Here is the broken ...

AngularJS directive doesn't refresh template when scope values are fetched dynamically through ajax requests

Attempting to give this question a precise title as possible, I find myself struggling with an issue in AngularJS. While trying to showcase my problem through a jsfiddle, it turned out to be too reliant on multiple files and not yet accessible online. So p ...

Discovering how to choose an element from a list fetched through ajax in Angular

It's quite strange to me. Angular allows for selecting by reference, but not by value. Let me explain my situation: I have a form that lets users edit a model. I use ajax to fetch both the model and a list of possible values for one of the model&apo ...

Utilizing AngularJS HotTowel to trigger a spinner when making AJAX requests

I am attempting to trigger the spinner whenever there is an xhr call within the application. Currently, the spinner only appears when clicking on a menu or navigating to a different page. Index page <aside class="main-sidebar"> <!-- ...

Invalid number of arguments for pure functions

I am currently facing an issue in angular2 (rc-1) where I am passing an array of strings to my function through component binding. However, when the array length exceeds 10, an error occurs: Unsupported number of argument for pure functions: 11 This erro ...

Angular JS basic API: Displaying only information that starts with the term 'request'

I've been given the task of developing a straightforward AngularJS API. I have managed to set up the basics for displaying data, but I'm facing an issue where the table only retrieves data from the JSON file if it starts with "request". As a resu ...

Is your AngularJS code throwing an error?

$scope.logout = function () { //var auth_token = $cookieStore.get('auth_token'); Auth.delete({ 'auth_token': $cookieStore.get('auth_token') }, function(data){ $scope.isLoggedIn = false; $cookieSto ...

The functionality of $watch in AngularJS is not meeting the desired outcomes

Within my controller, I am looking to receive notifications when the value of a certain variable changes. Specifically, I want a function to be triggered whenever this variable is updated. To achieve this, I am utilizing the $watch method in AngularJS. Her ...

Execute the function when the control becomes visible

Currently, I possess an input control: <input id="someID" class="form-control" type="text" name="SomeData" data-ng-model="vm.SomeData"> I have a requirement to set the initial value of vm.SomeData upon user scrolling down to this control. As a begi ...

The ng-checked attribute is not working as expected and being overlooked for the checkbox

I am facing an issue with a checkbox in my code. The checked state (ng-checked) of the checkbox is determined by a computed property (ng-checked="someFunction()"). Let's say the checkbox should always be checked, meaning the value should be ng-checke ...

Troubleshooting: Issue with AngularJS Image onload directive - "this" reference not functioning properly?

I have a custom directive that looks like this: .directive('ngImageOnLoad', function () { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('load', function() { ...

Changing the Date Format in AngularJS: A Step-by-Step Guide

I have a date coming from the database in the format "2015-09-21 18:30:00". I need to change it to 'dd/MM/yyyy'. I attempted it like this {{obj.added_date | date : 'dd/MM/yyyy'}} It displays as: 2015-09-21 18:30:00 | date : 'dd/ ...

An error has occurred: Noty (notification library) is not defined in this AngularJS Web Application

I am currently diving into the world of AngularJS and building a web application from scratch. As a newbie to AngularJS, I want to point out that I might be missing something crucial. An issue has arisen: After installing the Noty library (npm install no ...

mdDialog select an item based on its unique identification number

I am attempting to retrieve the width of a div within an mdDialog. However, the controller for the dialog runs before the HTML content loads, causing the selector to not find anything. Is there a way to employ the window.onload() or document.ready() functi ...