Attempting to close a basic angular modal leads to an error message stating: Property 'dismiss' cannot be read because it is undefined

I am attempting to create a straightforward modal that appears when a user clicks on a section of my demo app that is still in progress.

Everything is functioning correctly until the point where I require the user to click the 'Close' button on the modal. Upon doing so, they encounter the following error:

TypeError: Cannot read property 'dismiss' of undefined

This is the code snippet from my main controller:

    $scope.underConstruction = function () {
    var modalInstance = $modal.open({
        templateUrl: 'app/shared/underconstruction.html',
        controller: 'ModalInstanceCtrl',
        size: 'sm',
        resolve: {
            '$modalInstance': function () { return function () { return modalInstance; } }
        }
    });
    console.log('modal opened');
    modalInstance.result.then(function (response) {
        $scope.selected = response;
        console.log(response);
    }, function () {
        console.log('Modal dismissed at: ' + new Date());
    });
};

In my ModalInstanceCtrl, I have the following code:

app.controller('ModalInstanceCtrl', ['$scope', '$modal', function ($scope, $modal, $modalInstance) {
$scope.cancel = function () {
    $modalInstance.dismiss('cancel');
};
}]);

I am utilizing angular-ui version 0.12.0 and angularjs version v1.3.11

Despite reaching the close() method, the aforementioned error is triggered.

While researching potential solutions, I came across references to bugs and other issues, although the scenarios were more elaborate than mine - my modal simply displays some text and a close button. For instance, I encountered an answer on Stack Overflow which stated:

$modalInstance is made available for injection in the controller by AngularUI Bootstrap implementation. So, we don't need any effort ro "resolve" or make it available somehow.

Answer №1

I managed to simplify the process:

$scope.displayMessage = function () {
    var modalWindow = $modal.open({
        templateUrl: 'app/shared/message.html'
    });
    console.log('modal displayed');
};

Next, in my modal template:

  <button class="btn btn-primary" ng-click="$dismiss('cancel')">Close this message</button>

According to the guidelines provided:

Furthermore, the scope linked with the content of the modal is enriched with 2 functions:

$close(result)

$dismiss(reason)

These functions facilitate closing a modal window without needing a separate controller.

I attempted this previously, but it seems like either another factor was causing issues or I failed to clear my cache.

Answer №2

Ensure you clearly "defined" the $modalInstance parameter as undefined by failing to declare it as a dependency in your Inline Annotation Array when defining the ModalInstanceCtrl controller.

The correct declaration should have been:

['$scope', '$modal', '$modalInstance', function($scope, $modal, $modalInstance){ ... }]

Simply stating "we don't need any effort..." does not exempt you from specifying it as a dependency.

Answer №3

it's effective for me

if(typeof(alert/popover)!=="undefined"){
    await alert/popover.close();
  }

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

Incorporate Bootstrap into your Bigcommerce stencil theme for seamless design integration

As a newcomer to BigCommerce's Stencil theme, I am looking for guidance on integrating Bootstrap into the theme for local development. Is it feasible to incorporate custom CSS and JS into the Stencil theme as well? ...

Display the translated text to the user while storing a different value in the database using AngularJS and Angular-Translate

Currently utilizing AngularJS and attempting to utilize $translate for translations. I am facing an issue with a dropdown list where I display translated options for the user. For instance, in English = "Red" and in French = "Rouge", etc. The problem ar ...

AngularJS $http with a specific URL has a $timeout

Check out this code snippet: JavaScript: let timer; $scope.fetchDataFromApi = function(n){ let url = n; $http({ method: 'GET', url: url, }) .then(function successCallback(data) { ...

Steps to activate highlighting for the initial value in a quarterly datepicker

Concerning the quarterPicker feature in the Bootstrap datePicker (SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters, jsfiddle: jsFiddle): Is there a way to highlight an initial value upon startup? I have tried setting a value in win ...

Is there a way to insert rows and columns into the table headers using React Material UI?

I am new to working with material UI and I am having trouble figuring out how to add columns in the table header. The image below shows what I am trying to achieve - under "Economics", there should be 3 columns, each of which will then have two more column ...

Making an HTTP POST request in AngularJS

Upon sending a POST request with headers specified as content-type: application/JSON, the cookie is not being set in the Request Headers. However, when I modify the headers to be content-type: application/x-www-form-urlencoded, the cookie is successfully ...

Error: ng-messages syntax issue with the field parameter

Encountering the following error: Syntax Error: Token '{' invalid key at column 2 of the expression [{{field}}.$error] starting at [{field}}.$error]. when attempting to execute the code below (form-field.html) <div class='row form-grou ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

Steps to include all dependencies in an angular application

Managing a large Angular application can be challenging. I currently use npm install to install all packages and manually load them in my index.html file, like this: <script src="node_modules/angular/angular.js"></script> Similarly, I load ot ...

Update HTML page sections dynamically when there is a modification in the database table (specifically, when a new row

On my website, users can participate in betting activities. Whenever a user places a bet, a new entry is added to a mysql table. I am looking for a solution to refresh specific sections of the HTML page (not the entire page) whenever a user makes a bet (u ...

Transferring an Excel file through an HTML form input to a Java REST method

How can I submit an excel file from an HTML form input field and send it to a RESTful Java method for processing? I am integrating AngularJS into my project as well. ...

Angular 2 Issue: Error Message "Cannot bind to 'ngModel'" arises after FormsModule is added to app.module

I've been struggling with the data binding aspect of this tutorial for over a day now. Here's the link to the tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt1.html The error I keep encountering is: Unhandled Promise rejection: Tem ...

Is it possible to simultaneously run both an npm server and a proxy in separate directories with just one command in

We are currently working on a project that involves a 'server' folder and a 'client' folder. In order to run the project, we have to navigate to the 'server' folder, enter 'npm run nodemon' in the terminal, and then ...

How to Adjust Bootstrap Interval Dynamically

Here's a neat trick to set the interval of your bootstrap carousel: $('.carousel').carousel({ interval: 4000 }); But what if you want each slide to have a different interval? I decided to add data-interval attributes to each slide lik ...

What is the best way to compare JavaScript arrays with the same items but in a different order?

Within my product groups, each group is identified by a set of product_type_ids. I am looking for a way to match different groups based on their product_type_ids. The order of the ids may vary within the group, but as long as the sets of ids match, I cons ...

Javascript splice method mistakenly eliminating the incorrect elements

I have an array of objects like the one below: [{"name":"Rain"},{"name":"Storm"},{"name":"Forest"}] These objects are indexed as follows: [0, 1, 2]. I'm attempting to delete an item at a specific position using this code: $scope.selectedSound ...

Ways to run evaluations on 'private' functions within an angular service using Karma and Jasmine

In my Angular application, I have a BracketService that consists of various functions for comparing weights and creating brackets based on weight groups. The service includes functions like compareByWeight, filterWeightGroup, and createBracketsByWeightGrou ...

Problems with the functionality of the remote feature in Twitter Bootstrap Modal

Utilizing Twitter Bootstrap, I aim to retrieve HTML from another page and inject it into the modal on my current page. This led me to create a JavaScript function to facilitate this process. Within my 'index.php' file, I include the following: ...

No data returned from AngularJS $q.all

I desperately need assistance with the following problem. I am querying Firebase to retrieve a list of tasks sorted by priority (task date), then iterating through the results. For each task, I am fetching its related job from another branch in Firebase, a ...

The ui-routing function in $state.go fails to recognize custom parameters

I've implemented a 'go' back feature that redirects the user to the advSrch screen/state. If I set loadSearchQuery to true, it should load the search query. $scope.back = function() { $state.go('advSrch', { isDeleted: false, ...