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

Is there a way to apply toggling and styles to only the card that was clicked in Vue.js?

DisplayBooks.vue consists of a single page responsible for showcasing books fetched from a backend API. Each card on the UI features two buttons - ADD TO BAG and ADDED TO BAG. When a user clicks on the ADD TO BAG button of a specific card, it should toggle ...

Having difficulty establishing a connection between my node.js application and the database

I've been struggling to establish a connection between my application and the database. Despite attempting the code below, my models are still not being recognized. const MongoClient = require('mongodb').MongoClient; const assert = require(& ...

Having trouble importing a package into my React boilerplate

Having trouble importing the react-image-crop package with yarn and integrating it into a react boilerplate. Encountered an error after installing the package: Module parse failed: /Users/...../frontend/node_modules/react-image-crop/lib/ReactCrop.js Unex ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

The Angular component is failing to display the template

After following a tutorial on UI-Router () I have implemented the following states in my Angular application: angular .module('appRoutes', ["ui.router"]) .config(['$stateProvider', '$urlRouterProvider', function($sta ...

Inquiries regarding the distinctive key and component framework of Ant Design

Currently, I am in the midst of a project utilizing react, next.js, and antd. However, an error message has popped up stating: Warning: Each child in a list should have a unique "key" prop. This issue precisely stems from the absence of a uniqu ...

Switch up your code and toggle a class on or off for all elements that share a specific class

I've been attempting to create a functionality where, upon clicking a switch, a specific class gets added to every element that is assigned the class "ChangeColors". Unfortunately, I have encountered some difficulties in achieving this task. The error ...

Issues (forEach@, loadModules@, createInjector@, workFn@) encountered while conducting tests on $controller enhancement

I have applied a decoration to the controller named "originalCtrl" through the $controller service: //module declaration angular.module('decorationModule', [ 'originalModule', 'ExternalService' ]) //de ...

Transforming a group of JSON objects into a two-dimensional array

Below is an array of JSON objects: var data = [{ 1: { name: 'Name 1', id: 'one' } }, { 2: { name: 'Name 2', id: 'two' } }]; I want to transform this into a 2-D array like this: var newData ...

When trying to apply styles using ng-style attribute with jQuery, Angular does not seem to

Check out this plunker showcasing the issue : http://plnkr.co/edit/1ceWH9o2WNVnUUoWE6Gm Take a look at the code : var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { console.log('yeah'); ...

JavaScript Code to Remove an Element from an Array

I have a Javascript Filter Item Class and an array structured as follows: function FilterItem(filterId, filterType) { this.filterId = filterId; this.filterType = filterType; } var filterItemArray = []; To add Filter Items to this array, I use th ...

Creating a Personalized Tab Layout with react-bootstrap

Incorporating react-bootstrap components and styled components, I have implemented tabs in my project. The current appearance of the tabs is as shown here: https://i.sstatic.net/rPnlO.png However, my requirement is to have the tabs look like this inst ...

Leveraging JSON for parsing xmlhttp.responseText to auto-fill input fields

Is there a way to utilize JSON for parsing xmlhttp.responseText in order to populate textboxes? I've been struggling to achieve this using .value and .innerHTML with the dot notation, along with b.first and b.second from the json_encode function in th ...

Is it necessary for me to authenticate jwt tokens?

Let me explain my situation. I have generated a JWT token and stored it in Redis with a TTL of 1 hour. Now, most tutorials suggest using jwt.verify to authenticate the token. I understand that jwt.verify is used to verify whether the token is authentic or ...

Learn how to dynamically disable a button based on the input state matching an email pattern!

I'm facing an issue with my login form that has 2 input fields and a login button. One of the input fields requires a valid email pattern. If any of the input fields are left empty, the login button becomes disabled. However, when an incorrect email p ...

Leveraging the power of AngularJS controllers with jQuery's $.ajax functionality

Is there a way to utilize jQuery's $.ajax() function within an angularJS controller (instead of using angularJS built-in $http) in order to access $scope values from a view/template later? Below is an example of a somewhat minimalistic angularJS cont ...

Facebook and the act of liking go hand in hand, growing together

I am working on a website where I want to include Facebook like and share buttons with counters. To achieve this, I used Facebook's own links to generate these buttons for the specific URL. The issue I encountered is that when I like or share the page ...

Breaking down objects and setting default values

In need of assistance with resolving an issue related to default parameters and object destructuring. The 'product' object that I am working with has the following structure: { name: "Slip Dress", priceInCents: 8800, availableSizes ...

Tips for customizing the CSS styling of the validation ng-class error

Seeking advice: Is there a way to customize the CSS style of the 'error' validation error for ng-class in Bootstrap v3? This is my current code: ng-class="(form.datos.$invalid) && ( form.datos.$touched || submitted) ? 'error&apos ...