Angular's UI Modal: utilizing inline template and controller functionality

I am looking to create a simple confirmation box using UI-modal, which I have used successfully for more complex modals in the past that load their template and controller from external files.

However, this time I want something even simpler - just a basic box with a close button connected to a controller declared directly on the modal instance.

I attempted the following without success...

var modalInstance = $modal.open({
    template: "<div>Message goes here...<button ng-click='cancel()'>Continue</button></div>",
    controller: function(){

        $scope.cancel = function(){
            alert("Cancelled");
        };

    }
});

Answer №1

It appears that injecting $scope into your controller function is necessary.

controller: function($scope){

The scope of the modal template differs from the scope of the controller where the modal instance is declared.

Although $scope is a closure variable and adding .cancel() to it may work fine, the ng-click directive may not recognize .cancel() in its scope since it's not the same as the modal's scope.

I have replicated the issue in this jsbin: http://jsbin.com/gejuxije/2/edit

Edit: Since you mentioned avoiding external files for a template, here's a demonstration on how to include the modal template within the view's template where it is used.

http://jsbin.com/gejuxije/2/edit

You can embed HTML code within an inline script...

<script type="text/ng-template" id="myModalTemplateName.html"></script>

Answer №2

Ensuring that the value passed to 'template' is valid HTML is crucial, and it's recommended that it includes the necessary modal CSS classes.

Additionally, providing the scope for the controller may also be required.

var modalInstance = $modal.open({
    scope:$scope,
    template: "<div>Message goes here...<button ng-click='cancel()'>Continue</button></div>",
    controller: function(){
        $scope.cancel = function(){
            alert("Cancelled");
        };
    }
});

In my experience, I haven't encountered this issue before, but since you are defining the controller in the open method, it might be necessary. The documentation states that it should create a new scope as a child of rootScope, but there could be variations in its behavior. It would have been helpful if the website provided more detailed instructions on this matter.

You might also want to experiment with using $close and $dismiss. Although I haven't personally used them, if you're facing difficulties with the scope variable, these functions could potentially resolve the issue.

Answer №3

While working on a recent project, I came across this helpful tip that I wanted to share. Even though it's an older method, it can still be useful for someone.

To implement this feature, you can simply include the following line of code:

modalInstance.close(); 

This should be included in the cancel function of your application.

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

Issue with dynamic creation of menu in React Material UI where onClose function is unable to reference a variable inside the function

As I develop an app, I have chosen to dynamically construct the settings menu based on a JSON file. { categories: [ { name: "General", index: 1, items: [{ name: "Dark Mode", index: 1 ...

Pattern for validating mobile numbers with extensions using regular expressions

I am struggling to combine multiple separate regex validations into one for my mobile number validation requirements. The criteria include validating mobile numbers with a country code or starting with 00, as well as checking if they contain an extension n ...

Can someone guide me on implementing Node.js clusters in my basic Express application?

— I have successfully developed a basic application that retrieves data (50 items) from a Redis DB and displays it on localhost. After running an ApacheBench test with parameters c = 100, n = 50000, I am achieving around 150 requests/sec on my aging dual ...

modify the color of a box within a grid upon clicking it

I am curious if it is possible to change the color of a box when it is clicked. I am working on coding a "calculator layout" and would like to start with this part 1 2 3 4 5 6 7 8 9 0 This is what I have been working on and struggling with. $(docume ...

Monitor the number of ng-repeat items altering within a directive

I am using the angular-sly-carousel directive to display some data. The data is dynamically added as the user scrolls down, so I need to reload the sly carousel options after scrolling. Is there a way to detect when the length of ng-repeat elements change ...

Saving an array within the Yii framework

The view contains the following form: <form method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/telephone/addnow/" role="form" enctype="multipart/form-data"> <label>Upload your photo:</label><input type="fi ...

Generate a new document and input information using the ionic framework

I'm currently working on an application for mapping purposes. I have generated KML and JSON strings that need to be stored in files within the phone's memory. To achieve this, I implemented the following code: var fileObject; document.addEve ...

Modify the td attributes while retaining the extracted data values from the website

I'm currently utilizing this code to extract data from another website: $searchURL = "http://www.anotherwebsite.com"; $html = file_get_contents($searchURL); $patternform = '/(<tbody.*<\/tbody>)/sm'; preg_match_all($patternfor ...

Understanding the Behavior of Vue 3's setInterval Methods

Environment I am working on a Vue 3 Application where I need to run a constant setInterval() in the background (Game Loop). To achieve this, I have placed the code in store/index.js and invoked it from views/Playground.vue's mounted() lifecycle hook ...

Issue encountered in Vite Preview: Uncaught (in promise) SyntaxError: JSON.parse found an unexpected character at the beginning of the JSON data, line 1 column 1

Encountering the error message Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data when running vite preview after running vite build. Here is my vite.config.js: import { defineConfig } from "vite&q ...

Exploring the depths of JSON using @attributes and @association in the realm of JavaScript and AngularJS

Currently, I am working on a project that involves utilizing an API for data retrieval, updates, and deletions. The API in question is the prestashop API. While I have managed to retrieve data and update certain items successfully, I encountered an issue. ...

Steps for refreshing Google reCAPTCHA on an AJAX-enabled webpage

I am encountering an issue with two captchas on my website. One captcha is loaded upon refresh, while the second captcha is loaded on a different page via ajax. The problem arises when I click on the "No" button after selecting it on the second page. I wan ...

Utilizing a material-ui button within a React application as the trigger for a Popup using MuiThemeProvider

I want to trigger a Popup in React using a button with a custom theme: <PopUp modal trigger={ <MuiThemeProvider theme={buttonTheme}> <Button variant="contained" color="secondary">Excluir& ...

The passport authentication process is malfunctioning as there seems to be an issue with the _verify function

Having an issue and could use some assistance. I am currently implementing passport in my express application. While I am able to successfully register a user, I encounter an error when trying to log in. TypeError: this._verify is not a function at Str ...

Transforming a REST API get call into GraphQL

I'm currently using a REST API that accepts a code parameter, searches the database for matches, returns results if the parameter exists, and redirects users to a long_url retrieved from the database. How can I convert this functionality to GraphQL? i ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...

Angular 2 decorators grant access to private class members

Take a look at this piece of code: export class Character { constructor(private id: number, private name: string) {} } @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{character.name}} detai ...

I have a query related to material-ui 4, specifically the material-ui/pickers component that is reporting an error regarding a non-existent "mask" property

Recently, I upgraded a reactjs project that uses Material-UI (mui) from version 3 to version 4 by following the recommended migration guide. In the process, I also replaced material-ui-pickers 2.2.1 with @material-ui/pickers. However, after the upgrade, t ...

Extract data from a JSON object sent from an Angular frontend and process it in a C# ASP.Net

Having trouble creating a new Salesman with Angular and C#. I am collecting user input data in an array (newData) from my Angular controller and sending it to my C# server-side controller through a service. However, I am encountering errors and unable to r ...

Stopping free jqgrid disabled toolbar buttons from reacting to mouse clicks can be achieved by implementing specific coding techniques that

When using Free jqgrid, toolbar disabled buttons may trigger click events on mouse clicks which can lead to invalid code execution. To demonstrate this, open the page below in Chrome and click on a disabled inline edit or pager button. A rectangle will app ...