Is it possible to utilize both $uibModal and $uibModalInstance within the same controller to create a modal popup in an Angular project incorporating TypeScript?

Being new to Angular with Typescript, I encountered an issue while trying to implement a modal popup in Angular. The problem arises when I have a dropdown menu that triggers the opening of a modal popup with two buttons, "Yes" and "No". To handle this, I have a controller where I injected a dependency.

export class QuestionnaireController {
    static ngControllerName = 'questionnaireController';
    static inject = ["$uibModal"];
    constructor(private $uibModal: ng.ui.bootstrap.IModalService) {
    }
     public openModalPopup() {
        let options: ng.ui.bootstrap.IModalSettings = {
            controller: QuestionnaireController,
            controllerAs:'ctrl',
            templateUrl: 'app/views/Dialogbox.html',

        };
      this.$uibModal.open(options);

    }
}

While most of my code is in the 'QuestionnaireController' and the popup opens using this controller, I also need a way to close the popup. After reading an article, I learned that creating a new controller called "ModalController" would allow me to close the popup.

export class ModalController {
    static inject = ["$uibModalInstance"];
    constructor(private $uibModalInstance: ng.ui.bootstrap.IModalServiceInstance) {
    }
    public close() {
        this.$uibModalInstance.close();
    }
}
Popup code goes here...

<div ng-app="" id="dvModal">
<div class="modal-header">

</div>
<div class="modal-body">
    <p> Evaluated result will be discarded if you continue. Are you sure you want to continue?</p>
</div>
<div class="modal-footer">
    <input id="yesBtn" type="button" class="btn btn-default" ng-click="ctrl.Yes('true')" value="Yes" />
    <input id="npBtn" type="button" class="btn btn-default" ng-click="ctrl.close()" value="No" />
</div>

The challenge now lies in how to switch back to the "QuestionnaireController" to handle the "Yes" functionality, as it is written in the QuestionnaireController.

Answer №1

Absolutely!
$uibModal is an incredibly versatile tool.
While I'm not very experienced with Typescript, I have a JavaScript solution for you:

angular
.module('appName', ['ui.bootstrap'])
  .controller('SomePageController', ['$scope', '$uibModal', '$log',
    function ($scope, $uibModal, $log) {

To begin, you need to update your openModalPopup() method:

    // Create the modal window instance
    var modalPopup = function () {
      return $scope.modalInstance = $uibModal.open({
        templateUrl: 'blocks/modal/dialog.html',
        scope: $scope
      });
    };

    // Trigger the modal window popup 
    $scope.openModalPopup = function () {
      modalPopup().result
        .then(function (data) {
          $scope.handleSuccess(data);
        })
        .then(null, function (reason) {
          $scope.handleDismiss(reason);
        });
    };

    // Close the modal on Yes button click
    $scope.yes = function () {
      $scope.modalInstance.close('Yes Button Clicked')
    };

    // Dismiss the modal on No button click
    $scope.no = function () {
      $scope.modalInstance.dismiss('No Button Clicked')
    };

    // Log Success message
    $scope.handleSuccess = function (data) {
      $log.info('Modal closed: ' + data);
    };

    // Log Dismiss message
    $scope.handleDismiss = function (reason) {
      $log.info('Modal dismissed: ' + reason);
    }

  }
]);

Next - the modal window's HTML template would appear as follows:

<script type="text/ng-template" id="blocks/modal/dialog.html">
    <div class="modal-header">
      <h3 class="modal-title">I'm a modal!</h3>
    </div>
    <div class="modal-body">
      Modal content
    </div>
    <div class="modal-footer">
      <button class="btn btn-primary" type="button" ng-click="yes()">Yes</button>
      <button class="btn btn-warning" type="button" ng-click="no()">No</button>
    </div>
  </script>

Lastly - here's a straightforward SomePage HTML (in this case - Questionnaire) View example :

<div ng-controller="SomePageController">
  <button type="button" class="btn btn-default" ng-click="openModalPopup()">Open modal</button>
</div>

Putting it all together:

angular
  .module('appName', ['ui.bootstrap'])
  .controller('SomePageController', ['$scope', '$uibModal', '$log',
    function($scope, $uibModal, $log) {

      $scope.modalPopup = function() {
        modal = $uibModal.open({
          templateUrl: 'blocks/modal/dialog.html',
          scope: $scope
        });

        $scope.modalInstance = modal;

        return modal.result
      };


      $scope.modalPopupTrigger = function() {
        $scope.modalPopup()
          .then(function(data) {
            $scope.handleSuccess(data);
          },function(reason) {
            $scope.handleDismiss(reason);
          });
      };

      $scope.yes = function() {
        $scope.modalInstance.close('Yes Button Clicked')
      };

      $scope.no = function() {
        $scope.modalInstance.dismiss('No Button Clicked')
      };

      $scope.handleSuccess = function(data) {
        $log.info('Modal closed: ' + data);
      };

      $scope.handleDismiss = function(reason) {
        $log.info('Modal dismissed: ' + reason);
      }

    }
  ]);
<!DOCTYPE html>
<html>

<head>
  <link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body ng-app="appName">
  <div ng-controller="SomePageController">
    <script type="text/ng-template" id="blocks/modal/dialog.html">
      <div class="modal-header">
        <h3 class="modal-title">I'm a modal!</h3>
      </div>
      <div class="modal-body">
        Modal content
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" type="button" ng-click="yes()">Yes</button>
        <button class="btn btn-warning" type="button" ng-click="no()">No</button>
      </div>
    </script>

    <button type="button" class="btn btn-default" ng-click="modalPopupTrigger()">Open modal</button>
  </div>

  <script src="https://code.angularjs.org/1.5.7/angular.min.js"></script>
  <script src="https://code.angularjs.org/1.5.7/angular-animate.min.js"></script>
  <script src="https://raw.githubusercontent.com/angular-ui/bootstrap-bower/master/ui-bootstrap-tpls.min.js"></script>



</body>

</html>

Answer №2

For those of us who may be a bit on the lazy side, this alternative method could also do the trick ;)

var items = [{
 name: "item1",
 value: 1
}, {
 name: "item2",
 value: 2
}];

// Creating the modal HTML

var html = "<div class='modal-header'><h4 class='modal-title'>Choose Item</h4></div>";
html += "<div class='modal-body'>";
html += "<select class='form-control' ng-model='selection'>";
for (var i = 0; i < items.length; i++) {
 var itm = items[i];
 html += "<option value='" + itm.value + "'>" + itm.name + "</option>";
}
html += "</select>";
html += "</div>";
html += "<div class='modal-footer'>";
html += '<button type="button" ng-click="dismissModal()" class="btn btn-default" >Close</button>';
html += '<button type="button" ng-click="closeModal()" class="btn btn-primary">Select</button>';
html += "</div>";

// Displaying the modal

var itemSelectionModal = $uibModal.open({
 template: html,
 controller: function($scope) {

  // Function for closing the modal (when positive button is clicked)

  $scope.closeModal = function() {
   //Closing the model with selected result
    itemSelectionModal.close($scope.selection);

  };

  //Function for dismissing the modal (when negative button is clicked)

  $scope.dismissModal = function() {
   itemSelectionModal.dismiss();
  };

 }


});

//Handling the Result
itemSelectionModal.result.then(function(selected) {
 alert(selected);
});

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

Questions about setting up a controller in AngularJS

As I dive into my first AngularJS controller within a test application, I am encountering some challenges. I am retrieving a list of items from a RESTful web service and working on implementing basic CRUD logic for these items. The item list is displayed ...

Angular causes HTML Dropdown to vanish once a null value is assigned

In my scenario, I have two variables named power and mainPower. Both of these variables essentially represent the same concept, with mainPower storing an ID of type Long in the backend, while power contains all attributes of this data transfer object. The ...

When I attempt to add a todo item by clicking, the Url value is displayed as "undefined"

I am facing an issue with my household app where, upon clicking the button to navigate to the addtodo page, the URL specific to the user's house is getting lost. This results in the todolist being stored as undefined on Firebase instead of under the c ...

Develop a dynamic webpage using ASP.NET for enhanced interactivity

Currently, I am working with asp.net 2.0 and C#. I have a unique teacher-student dynamic in my platform, where I envision students receiving personalized pop-ups created by their respective teachers upon login. My challenge lies in providing teachers wit ...

How can I filter an array by a nested property using Angular?

I need help with objects that have the following format: id: 1, name: MyObj properties: { owners: [ { name:owner1, location: loc1 }, { name:owner2, location: loc1 } ] } Each object can have a different number of owners. I' ...

AngularJS - issue with directive functionality on dynamically inserted classes

Check out this plnkr - I've got a button that toggles the class toggled on the body element. I've also developed a directive to trigger an alert when the toggled class is applied to the body element, but for some reason it's not working. H ...

What are the steps for integrating mongoDB with an angular2 application?

I currently have my angular2 & mongoDB setup successfully. While I've managed to read JSON files using the HTTP service, my goal is to create a fully functional application with database connectivity as well. I'm seeking advice on how to con ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

Tips for setting up nextjs with typescript to utilize sass and nextjs font styles

I am attempting to configure a Next.js TypeScript app to work with Sass and a font in Next.js. I have been following the steps outlined in this article. Without the font module, styles are working correctly. Below is my next.config.js without the font co ...

Angular throwing "provider not found" error when attempting to inject service into controller

I've been diving into a project that incorporates the concept of IIFE, which I'm still in the process of wrapping my head around. My service appears to be functioning well; I've even used some Jasmine to confirm its definition. However, when ...

Detecting the check status of a checkbox in react native: a complete guide

I'm currently working on a scenario where I need to implement logic for checking or unchecking a checkbox in React Native. If the checkbox is checked, I want to print one string, and if it's unchecked, I want to print something else. How can I ac ...

Issue: Incorrect comparison of two dates leading to inaccurate results

I have been attempting to compare two dates within a UI-GRID, and although I have the dates in the correct format, it seems to always provide a false result. Below is the code: filters: [{ condition: function (term, value) { if (!term) return ...

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

What is the best way to implement a conditional check before a directive is executed in Angular, aside from using ng-if

I am facing an issue where the directive is being executed before the ng-if directive. Is there a way to ensure that the ng-if directive is executed before the custom directive? Could I be making a mistake somewhere? Should I consider using a different ...

Tips for breaking up array elements across multiple "tr" tags

In this particular example, I have a Fiddle set up with multiple tr elements displayed within an ng-repeat. My goal is to have three td elements per row. Would it be necessary to use an inner angularjs ng-repeat and split the iconDets array for this purpos ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

A helpful guide on performing a service call in AngularJs when attempting to close the browser tab or window

I am currently working on implementing a service call that will trigger when the browser tab or window is being closed. I was wondering if there is a way to make a RestApi call when attempting to close the browser tab or window. Does anyone have any sugge ...

What is the best way to access values from dynamically added components in Svelte when using data from a REST API in a loop?

Previously, I posted this query but now I've made changes to utilize a REST service for retrieving the item list. Everything functions as expected when the data is hardcoded, however, I encounter undefined values when using data from the REST service. ...

"Error: Import statement must be used within a module" encountered in TypeScript (with nodemon) and Node.js (running in Docker)

Within the server directory of my web application written in TypeScript, there is a nodemon command used to automatically restart the code after changes are made. The command looks like this: nodemon dist/index.js However, upon running it, an error is enc ...

Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Succes ...