Issue with ng-click not triggering the $mdDialog callback

Utilizing Angular Material, I have functionality in TasksCtrl that triggers a $mdDialog - utilizing the locals property to pass an object that will be changed in DialogCtrl before being returned to the view.

Nevertheless, the .then() callbacks do not trigger on ng-click. Although if I manually set a scope variable that is displayed elsewhere in the dialog, I can see the ng-click altering the value, but the only way to execute the .then() is by clicking outside of the modal.

TasksController (as TasksCtrl)

(function() {

    angular.module('ICP_App')
        .controller('TasksController', function(ToggleService, TasksService, $mdToast, $mdDialog) {
            var vm = this;
            vm.createTaskAttachment = function(ev) {
                $mdDialog.show({
                    controller: 'DialogController',
                    controllerAs: 'DialogCtrl',
                    templateUrl: '../partials/dialogs/create-task-attachment.tmpl.html',
                    locals: {
                        data: vm.selectedTask
                    },
                    parent: angular.element(document.body),
                    targetEvent: ev,
                    clickOutsideToClose:true
                })
                    .then(function(answer) {
                        alert('you submitted');
                    }, function() {
                        alert('you cancelled it');
                    });
            };
        })


})();

DialogController (as DialogCtrl)

(function() {

    angular.module('ICP_App')
        .controller('DialogController', function(data) {
            var vm = this;
            vm.selectedTask = data;
            vm.tempAttachments = [];

             vm.addTempAttachment = function(keypress, type) {

                if (keypress.which === 13) {
                    if (type == 'link') {
                        vm.tempLinkAttachment.category = 'link';
                        vm.tempAttachments.push(vm.tempLinkAttachment);
                        vm.tempLinkAttachment = {};
                    }
                }
             };

        })


})();

And the template file for the $mdDialog

<md-dialog aria-label="Create Attachment" flex-gt-sm="50">
    <form>
        <md-toolbar>

            <div class="md-toolbar-tools">
                <h2>Add New Attachment</h2>
                <span flex></span>
            </div>
        </md-toolbar>
        <md-dialog-content>
            <md-tabs md-dynamic-height md-border-bottom>
                <md-tab label="Link">
                    <md-content class="md-padding">
                        <div layout="row">

                            <div flex>

                                <!-- Add new action -->
                                <div layout="column" layout-gt-xs="row" class="new-entry-line">

                                    <div flex-gt-sm="50">

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

                                            <input ng-model="DialogCtrl.tempLinkAttachment.Title" placeholder="Title...">

                                        </md-input-container>

                                    </div>

                                    <div flex-gt-sm="50">

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

                                            <input ng-model="DialogCtrl.tempLinkAttachment.Link" placeholder="Link..." ng-keypress="DialogCtrl.addTempAttachment($event, 'link')">

                                        </md-input-container>

                                    </div>

                                </div>

                            </div>

                        </div>
                        <div layout="row">
                            <div flex>
                                <md-list>
                                    <md-list-item md-2-line ng-repeat="attachment in DialogCtrl.tempAttachments | filter: {'category': 'link'}">
                                        <md-icon md-svg-icon="content:ic_link_24px"></md-icon>
                                        <p>{{ attachment.title }}</p>
                                    </md-list-item>
                                </md-list>
                            </div>
                        </div>
                    </md-content>
                </md-tab>
                <md-tab label="File">
                    <md-content class="md-padding">
                        <div layout="row" layout-align="center">
                                <md-button flex="30" class="md-primary md-raised">Upload</md-button>
                        </div>

                    </md-content>
                </md-tab>


            </md-tabs>

        </md-dialog-content>
        <md-dialog-actions layout="row">
            <md-button ng-click="answer('Not useful')">
                Not Useful
            </md-button>
            <md-button ng-click="answer('Useful')">
                Useful
            </md-button>
        </md-dialog-actions>
    </form>
</md-dialog>

Answer №1

Sharing data between the dialog and the main controller can be achieved using the following approach - CodePen Example

The usage of $scope for this purpose is recommended in the official documentation available at docs:

Remember to enable preserveScope for proper functionality.

JavaScript Code:

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('TasksController', function($scope, $mdDialog) {
  var vm = this;
  vm.createTaskAttachment = function(ev) {
    $mdDialog.show({
      controller: 'DialogController',
      controllerAs: 'DialogCtrl',
      templateUrl: 'create-task-attachment.tmpl.html',
      parent: angular.element(document.body),
      scope: $scope,
      preserveScope: true,
      targetEvent: ev,
      clickOutsideToClose:true
    })
      .then(function(answer) {
      alert('Submission received: ' + answer);
    }, function() {
      alert('Action cancelled');
    });
  };

  $scope.$watch("vm.selectedTask", function () {
    if (angular.isDefined(vm.selectedTask)) {
      $mdDialog.hide(vm.selectedTask);
    }
  })
})

.controller('DialogController', function($scope, $mdDialog) {
  $scope.answer = function(answer) {
    $scope.vm.selectedTask = answer;
  }
})

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

Endless scrolling dilemma

I came across an example of infinite scrolling and attempted to implement it myself. Despite correcting all the errors I could find, it still refuses to work. Below is the directive code: module.exports = /*@ngInject*/ function scrollDirective($rootScope ...

Dynamically enhance dropdownlist options in webforms using JavaScript

I am currently working on an asp.net webforms project where I have a page with 2 dropdown lists. Whenever a user selects an option from ddl1, I want to dynamically add that selected element to ddl2 using JavaScript. Initially, when the page loads, ddl1 h ...

Emphasize Expandable Sections based on Search Term

I have been working on developing an HTML page for my company that will showcase a list of contacts in an "experts list". Currently, the list is structured using collapsible DIVs nested within each other. Additionally, the HTML page features a search func ...

Utilizing a custom keyboard with Jquery for a recurring function

It seems like I might be missing something simple here, as I am following the code tutorial provided in the link below: The goal of this project is to create a popup keyboard for a touch screen. Although I have made some modifications for specific purpose ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

Attempting to streamline the process of verifying the truthfulness of an object key and subsequently adding it to a different

In the process of creating a form to interact with a remote API, I aim to construct a GET request query string depending on which checkboxes the user chooses. Initially, I considered using a series of if/else statements to check whether the model object k ...

The reason behind angular expressions resulting in empty strings when evaluated within an attribute

What could be causing angular expressions within an element's attribute to evaluate as empty strings when there are multiple expressions present? In a specific scenario, I have an attribute with identical expressions that output scope variables. Howev ...

What is the goal of JSON.parse(JSON.stringify(x))?

During my recent project work, I stumbled upon the following code snippet: let newParams = JSON.parse(JSON.stringify(initialParams)); I'm curious - what exactly does this code achieve? ...

modify the name attribute of a select dropdown using jQuery dynamically

In my current project, I am working on dynamically changing the "name" attribute for each select box based on user interactions. The scenario is as follows: When a user clicks on an option in the first select box, a new select box appears with the remainin ...

HTML, JavaScript, and PHP elements combine to create interactive radio buttons that trigger the appearance and disappearance of mod

On my page, I have multiple foreach loops generating divs with different information. These divs are displayed in modals using Bootstrap. However, I am encountering an issue where if I select a radio button and then close the modal and open another one, th ...

Tips for initiating a browser file download using JavaScript, ensuring that the download is only carried out if the web service responds with

For a project I am working on, I need to create JavaScript code that will be triggered by clicking on an <a> element. This code will then make a GET request to a web service that I am currently in the process of coding. Once the service returns a fil ...

What is the best way to refresh an angularjs page once the scope has been updated?

I have created a custom directive that captures keyboard events and updates certain objects in the scope based on the keys pressed. The goal is to navigate through an array and display details of the selected row. However, I am facing an issue where the pa ...

What is the process for playing an audio file on a mobile device?

Recently, I encountered an issue with a jQuery statement that plays a created audio file. Strangely, the file plays correctly on my computer but not on my mobile phone. Despite max volume settings, there is no sound when trying to play it on the mobile dev ...

Incorporating Distinct Items into an Array with JavaScript

There is a Filter object that stores information about different Car Types. The data is fetched via AJAX calls - on the first call, objects 0-10 are created and added to an array. Subsequent calls bring more car types which are also appended to the array. ...

The bundle.js file encountered an issue while running UglifyJs, expecting a name

I have been attempting to utilize UglifyJS to compress/minimize my bundle.js file. However, when executing webpack -p, I encountered the following error message: ERROR in bundle.js from UglifyJs Name expected [bundle.js:105519,6] The line causing the iss ...

What is the best way to activate the default action/event of an HTML link (anchor element)?

Is there a way to programmatically trigger the default action of an HTML link using JavaScript or jQuery? Essentially simulating a user click on the link. Simply using .click() does not seem to do the trick. $('#alink').click(); // nothing happ ...

Looking to show the contents of a Rails AJAX JSON response in your application? Having trouble with Javascript displaying [object HTMLDocument] instead? Let

I have been working on a Rails application where I implemented an AJAX / JSON controller to facilitate dynamic HTML updates within the view. For guidance, I referred to this helpful resource: When making a call like this: ../related.json?vendor_id=1&b ...

Python Selenium test on AngularJS UI slider implemented

I've been experimenting with setting up a UI slider (Label=ON/OFF, Slider, Apply button) using Angular JS in combination with selenium. Here's an example of the code I've been working on: jsfiddle In my attempts, I tried using the followin ...

The presence of a Bootstrap addon is resulting in horizontal scrolling on mobile devices within the webpage

I am encountering a peculiar issue with an input-group in my cshtml file which features a Bootstrap addon. The problem arises on mobile devices, where upon focusing on the input field, the page scrolls horizontally to the right, revealing the right margin ...

Issue with React Material UI: Snackbar is closing when Dialog closes which is not the intended behavior

When using Material UI dialog, it unexpectedly closes the snackbar as well. To illustrate this strange issue, I have prepared a demonstration: https://codesandbox.io/s/react-hooks-counter-demo-v20w3 I am passing states from the parent component to the c ...