How to use ng-click for a function in a directive with a custom template in Angular Material's $mdDialog?

In my project, I have utilized the $mdDialog.show() method within a custom directive to display a dialog with a custom template. This template includes two buttons - 'Cancel' and 'Confirm'.

I am facing an issue with calling functions named 'cancelLeaver()' and 'confirmLeaver()' from these buttons, which need to be defined in the directive itself.

Although I tried to use the $mdDialog.then() feature, it did not work as expected due to the presence of buttons in the custom view template.

Can someone guide me on how to execute functions referenced in a view template's ng-click attribute when they are written inside a separate directive?

HTML:

<md-dialog ng-controller="mainController" style="min-width: 30vw">

<md-dialog-content>

    <h2 class="md-title">Confirm leaver status</h2>

</md-dialog-content>

<md-dialog-content class="minus-padding-top">

    <p>Enter employee's leave date below</p>

    <br>

    <md-input-container class="md-prompt-input-container">

        <input id="leaveDate" name="leaveDate" ng-model="employee.leaveDate" ng-init="employee.leaveDate = currentDate" aria-label="Leave Date" required>

    </md-input-container>

</md-dialog-content>

<md-dialog-actions>

    <md-button ng-click="cancelLeaver()">Cancel</md-button>

    <md-button ng-click="confirmLeaver()" ng-disabled="!employee.leaveDate.length">Confirm</md-button>

</md-dialog-actions>

</md-dialog>

Directive:

app.directive('makeLeaver', function($window, $mdDialog, $mdToast, $timeout, $state) {
return {
    restrict: 'A',
    scope: {
        employee: '=',
    },
    controller: 'employeeDetailsController', 
    controllerAs: 'employeeDetails',
    bindToController: true,
    link: function(scope, element, attrs) {
        element.bind('click', function() {

            console.log('makeLeaver(' + '#' + scope.employee.id + ')');

            /* Show confirmation prompt dialog */
            $mdDialog.show({
                parent: angular.element('body'),
                clickOutsideToClose: true,
                templateUrl: 'views/employees/employeeDetails/dialogs/makeLeaver.html',
                targetEvent: element
            })

            /* ---------------- TRIED THIS BUT DIDN'T WORK ---------------- */
            scope.cancelLeaver = function() {
                console.log('cancelLeaver()');
                $mdDialog.hide();
            }

            scope.confirmLeaver = function() {
                console.log('confirmlLeaver()');
            }

        })
    }
}
})

Answer №1

If you want to communicate between different components in AngularJS, there are a few methods you can use. One option is to use $rootScope.$broadcast('foo') and then listen for it elsewhere using $rootScope.on('foo'). Another approach would be to pass the scope through the function. For more information on this topic, you can refer to this tutorial.

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

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

jQuery fails to execute in ajax success function

Currently, I am using jQuery and Ajax to dynamically populate a select element. However, I am facing an issue within my success callback where my DOM manipulation is being ignored. An interesting observation is that even though my console.log('test&a ...

Getting the badge value of a button in Angular JS is a simple process that involves accessing

How can I retrieve the badge value of a Button? This badge represents data-text-as-pseudo-element and I am new to Angular. Can someone guide me on how to achieve this? <style type="text/css">[data-text-as-pseudo-element]::before { content: ...

Hear for updates on Firebase data using AngularFire

Can Firebase server updates be listened to in the DOM through AngularFire? I am looking for a way to automatically retrieve any updates from the server and use them to update an array's values. The issue I am facing is related to using Firebase.Serve ...

I'm having trouble accessing the data stored in req.user within the user controller, despite having integrated it into the user isLoggedIn middleware

I am encountering an issue where I cannot access my req.user in the usercontroller, even though I have implemented it in the usermiddleware. Both storing data in req.user and retrieving data using req.user from the middleware to my controller are not work ...

What could be the reason for the failure of @babel/preset-react automatic transformation with Webpack?

The setup involves a Yarn monorepo with a babel.config.js that specifies the environment. React version being used is 18.1.x. I have a similar configuration that works perfectly fine in another setup, but it's failing here. I've been painstaking ...

Utilize jQuery to manipulate a subset of an array, resulting in the creation of a new array through the use of

I have a string formatted like this: ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4 (and so on, up to item 25). My task is to take an index provided by the user (for example, 2), retrieve the item at that index when ...

Personalize the close button on the modal

Utilizing the angular strap modal in my controller looked like this: $scope.modal = $modal({ scope: $scope, title: 'My Title', content: text, html: true, contentTemplate: 'views/partials/myTemplate.html', show: ...

Accessing website login - <div> and validating user entry

I am currently working on developing a basic login webpage, but I am facing issues with the rendering of the page. Below is the code I am using: function logIn(username, password){ var username = document.getElementById("username").value; var p ...

Animating the continuous transformation of websites using Three.js

Recently, I came across a fascinating website called Garden-Eight that impressed me with its seamless transition between the "Home" and "About Us" sections. The transition was so smooth and continuous, without any loading screens or delays. Upon closer in ...

Extracting Data from Multiple Pages Using Python 3 without Changing URL

Recently, I delved into the world of web scraping and decided to try my hand at grabbing data from various websites. Currently, I'm focused on scraping information from the site - Using selenium, I've managed to extract longitude and latitude da ...

Creating dynamic form calculations using Javascript, Ajax, and JQuery on user input change

My form needs to be populated from a MySQL database and human input. The goal is to calculate 2 additional fields based on the existing ones. Example Form: Indicator (MySQL) (dropdown) Hour Equivalent (MySQL) SKS Equivalent (MySQL) Amount (User) Hour To ...

Paper.js - generate a collection of movable shapes

I am attempting to use paper.js to create draggable shapes where the index of each shape is provided during dragging. Unfortunately, I keep encountering an error that says "Uncaught TypeError: Cannot read property 'position' of undefined". If a ...

What is the best way to dynamically insert an item into an object?

Currently, I am storing the client and product details along with quantity in an array. Here is how it looks: var idCliente = $scope.myClient.codigo; var nombreCliente = $scope.myClient.nombre; var idProducto = $scope.myProduct.codigo; var ...

An error in syntax is being triggered by the Php file being accessed through the <script src="list.php"></script>

We're facing an unusual problem with our online ordering platform script that we purchased a few months ago. It had been functioning perfectly for several months, but now we're encountering an issue! The website page is not loading, and when we c ...

What are some ways to sort through JSON data efficiently?

I am in need of filtering JSON data based on specific parameters. When using the GET method at http://localhost:5000/api/car?bodyTypeId=2, I expect to receive only JSON objects with bodyTypeId equal to 2. However, all objects are being returned: [ { ...

Strange issue encountered with Ember controllers

I am currently using Ember Cli version: 0.2.3 Exploring Ember for the first time and experimenting with a simple app. This is what I have in my templates/about.hbs <h1>About</h1> <p>Adding something interesting here</p> <but ...

Tips for displaying a loading spinner each time the material table is loading

Hey there, I'm currently working on an Angular project where I need to display a table using Material Table. To indicate that the table is loading, I've defined a variable called isLoading. Here's how it works: In my TypeScript file: @Com ...

MongoDB does not recognize Db.Collection as a valid function

A lot of people have been inquiring about this specific error, but after thorough investigation, I couldn't pinpoint a similar issue. So I'm reaching out in the hopes that someone might be able to identify and help rectify it. Let me provide som ...

Scrolling in Angular UI-Grid does not function properly when displayed in a right

Issues arise in Google Chrome when the grid has scroll in RTL: Vertical scrolling causes rows to disappear Horizontal scrolling makes headers stick to the left while columns scroll No problems are found in Firefox. The column menu position is inaccurat ...