Tips for utilizing a shared controller in an Angular Material popup dialogue

Within my project, Angular Material is being used for various dialogs, primarily for alert purposes. However, I now find myself in need of a more complex dialog.

The example provided on the Angular Material site showcases how to create a dialog:

function showDialog($event) {
  var parentEl = angular.element(document.body);
  $mdDialog.show({
    parent: parentEl,
    targetEvent: $event,
    template: '<md-dialog aria-label="List dialog">' +
      '  <md-dialog-content>' +
      '    <md-list>' +
      '      <md-list-item ng-repeat="item in items">' +
      '       <p>Number {{item}}</p>' +
      '      ' +
      '    </md-list-item></md-list>' +
      '  </md-dialog-content>' +
      '  <md-dialog-actions>' +
      '    <md-button ng-click="closeDialog()" class="md-primary">' +
      '      Close Dialog' +
      '    </md-button>' +
      '  </md-dialog-actions>' +
      '</md-dialog>',
    locals: {
      items: $scope.items
    },
    controller: DialogController
  });

  function DialogController($scope, $mdDialog, items) {
    $scope.items = items;
    $scope.closeDialog = function() {
      $mdDialog.hide();
    }
  }
}

My question is whether it's possible not to specify a separate controller for the $mdDialog, but instead allow it to use the same controller from which it was called?

For instance, if triggered by this button, can the dialog simply utilize the existing MyCtrl controller to access scope variables?

<div ng-controller="MyCtrl">
  <md-button ng-click="showDialog($event)" class="md-raised">
    Custom Dialog
  </md-button>
</div>

Is this feasible, or do I need to continuously rely on the locals property and broadcasting to pass variables between controllers?

Answer №1

If you utilize `controllerAs`, it is possible to achieve that functionality. In my case, I am implementing it with ES6 in the following manner:

this.$mdDialog.show({
  targetEvent: event,
  templateUrl: 'path/to/my/template.html',
  controller: () => this,
  controllerAs: 'ctrl'
});

For those not using ES6, the code would appear as follows:

.controller('AppCtrl', function($scope, $mdDialog, $mdMedia) {
    var self = this;

    this.showTabDialog = function(ev) {
        $mdDialog.show({
            controller: function () {
                return self;
            },
            controllerAs: 'ctrl',
            templateUrl: 'tabDialog.tmpl.html',
        });
    };
});

This is an adaptation of the basic usage example provided in the documentation: http://codepen.io/kuhnroyal/pen/gPvdPp

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

Need to get an item from a collection at the library?

Is it possible to import and use an object from a library? For instance, suppose we have a file named data.js with the following content: return { "name": "Testing" } In the file index.js, could we do something like this: const data = require('. ...

Using useCallback with an arrow function as a prop argument

I'm having trouble understanding the code snippet below <Signup onClick={() => {}} /> Upon inspecting the Signup component, I noticed the implementation of useCallback as follows const Signup = ({onClick}) => { const handleClick = us ...

Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particul ...

I encountered an error while trying to add a document to Firestore using the 'add' method in Vue.js. Can someone provide guidance on how to

Whenever the function is triggered (on click), I aim to include a new document. Although it functions with .set(), my goal is for a new document to be created each time the form is submitted. The current error code I am encountering is: https://i.sstatic ...

Tips for restricting camera movement in threejs

Being new to working with threejs, I am struggling to set limits on the camera position within my scene. When using OrbitControls, I noticed that there are no restrictions on how far I can zoom in or out, which I would like to change. Ideally, I want the c ...

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...

Utilizing JSON with AJAX to dynamically fetch data on a separate webpage results in the page reloading despite implementing the e.preventDefault() method

Looking to retrieve a value on a new page and navigate without refreshing? I'm utilizing the POST method here along with JSON to fetch values. Still learning the ropes of this Ajax code! My goal is to move from the team.php controller page to team_d ...

What is the process for integrating GitHub repository code into my client-side JavaScript application?

I am attempting to incorporate the GitHub repository "zipcelx" into my client-side JavaScript, but all I see is an option to download it from npm, which I do not understand. It would be helpful if someone could explain how a module meant for client-side us ...

Guide on managing firebase and webrtc tasks within a client-side component using Next.js 13

I developed a Next.js 13 application to share the camera feed using WebRTC and Firestore. Below is my page.tsx file where I am facing some challenges. I can't make this server-side because I'm using React hooks, and moving it to the client side i ...

The jQuery formvalidator plugin for file validation isn't functioning as expected

I am attempting to validate the file type input using the formvalidator.net plugin, however, I am not seeing any errors. What could be wrong with the code below? It is functioning properly for other types of input. Here is an example of what I am trying: ...

What are the steps to save data on a user's computer through a web browser?

Is it feasible to save data in the client's computer using a web browser and jQuery code to interact with the file system? ...

Avoiding repetitive rendering of child components in ReactJS

In my React project, I have a parent component that contains 3 children components, structured like this: var Parent = React.createClass({ render: function() { return (<div> <C1/> <C2/> <C3/> ...

Having trouble getting CSS absolute and relative positioning to work with my div slider carousel

I'm currently working on creating a slider carousel using VUE, where the CSS classes (3 divs) are looped through. However, I am facing an issue where every time a div fades out, the next slider creates a duplicate slider at the bottom, resulting in tw ...

Regular Expression: do not include comments that are placed inside quotation marks

Using the regular expression /#(.*?)\r?\n|#(.*?)$/g, I was able to parse the following content. However, it also matches the comment within the quotes. How can I prevent this from happening? # # this is a comment # but this is '# not a c ...

How can I convert JSON data from an array to an array of objects using JavaScript?

My goal is to load data into an ag-grid. I have obtained the json data in the following format: {"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}} In order to pass it to the grid, I need to transform it to this format: {"my_data":[{"labels" ...

Determining the height of the first element in jQuery

I am dealing with multiple elements that share the same class but have different heights. The class 'xyz' is only for styling borders, as shown below: <div class='xyz'></div> //1st element height=10px <div class='xy ...

Tips for creating a textarea element that resembles regular text format

I am working on creating an HTML list that allows users to edit items directly on the page and navigate through them using familiar keystrokes and features found in word processing applications. I envision something similar to the functionality of To achi ...

ajax always returns the same value, even when the input value is different

Each time I click on a different value, the console.log keeps giving me the same value. view image description I have checked the HTML code and found that even though each value attribute is different, it still returns the first value of the attribute. vi ...

Decoding JSON in Angular

Hey there, I'm facing a bit of a challenge. My Angular JSON GET process is grabbing the results properly, but I'm struggling to parse and access individual values from the result. Here's the string result that I receive: {"result":[{"sys_i ...

Using the googleapis library within HTML is not permitted

I have been attempting to execute a simple function (uploadFile(test.txt)) within an HTML file, but I am encountering issues as my app.js and Google APIs are not being recognized or called. Node.js is throwing this error: Uncaught ReferenceError: uploadFi ...