Using an external file to control the Angular $md-dialog

I have encountered a small issue while using md-dialog from Material Design that is causing me some trouble.

The dialog serves as a form for creating a new record in the database, and I need its controller to be loaded from an external file. This is because I am utilizing the same dialog in multiple places within the app (in various other controllers) and I want to avoid duplicating it in each one.

I attempted to write it as a service, but ran into a problem when binding data from the form to the controller using $scope, resulting in a "$scope is not defined" error. When I added $scope as a dependency in that service, I encountered an injection error. Do you have any suggestions on how to load the modal controller externally so that it works seamlessly with the use of $scope?

$scope.showNewContactDialog = function($event) {
            var parentEl = angular.element(document.body);
                $mdDialog.show({
                parent: parentEl,
                targetEvent: $event,
                templateUrl: 'app/Pages/directory/contacts/newContact.dialog.html',
                controller: NewCompanyContactDialogCtrl,
                clickOutsideToClose: true,
                hasBackdrop: true
            });  
        };

// New User dialog controller
        function NewCompanyContactDialogCtrl($scope, $mdDialog) {
            var self = this;
            $scope.modalIcon = "add";
            $scope.modalTitle = 'Nová položka';
            $scope.modalAdvanced = true;

            // Country Selector
            apiCalls.getData(countryUrl, function(response){
                $scope.countries = response;
            })

            // Add New Object
            $scope.newItem = function() {
                var url = baseUrl + 'new/';
                var data = JSON.stringify({
                    code: $scope.newItem.contactCode,
                    first_name: $scope.newItem.contactFirstName,
                    last_name: $scope.newItem.contactLastName,
                    street: $scope.newItem.contactStreet,
                    city: $scope.newItem.contactCity,
                    country: $scope.newItem.contactCountry,
                    postal: $scope.newItem.contactPostal,
                    pobox: $scope.newItem.contactPobox,
                    price_lvl: $scope.newItem.contactPriceLvl,
                    orgid: $cookies.get('orgid')
                });

                apiCalls.postData(url, data, function(response){
                    console.log(response);

                    // Toast
                    if(response.status == 201){
                        $mdToast.show(
                            $mdToast.simple()
                                .textContent('Záznam bol vytvorený.')
                                .position('bottom right')
                                .action('Skryť')
                                .highlightAction(true)
                                .highlightClass('md-warn')
                        );

                        $mdDialog.cancel();   
                    }
                });
            }

Answer №1

If you want to utilize a service, you can follow this example:

angular.module('myApp').factory('newCompModal', function($mdDialog){
        var parentEl = angular.element(document.body);

       function displayModal($event){
            return  $mdDialog.show({
                parent: parentEl,
                targetEvent: $event,
                templateUrl: 'app/Pages/directory/contacts/newContact.dialog.html',
                controller: 'NewCompanyContactDialogCtrl',
                clickOutsideToClose: true,
                hasBackdrop: true
            });

       }    
      return {
        show: displayModal
      }    
});

Then in any controller:

angular.module('myApp').controller('someController',function($scope,newCompModal){
        $scope.openNewCompanyModal = newCompModal.show;        
})

Remember to pass an event from the view:

<button ng-click="openNewCompanyModal($event)">New Company</button>

If you need to send data from the controller to the modal, you can add another parameter and include it in the locals property of $mdDialog, or share it through another service property.

Answer №2

Illustration of a dialogue with an external organizer:

$mdDialog.show({
    scope               : scope,
    preserveScope       : true,
    templateUrl         : 'template/search.html',
    targetEvent         : event,
    clickOutsideToClose : true,
    fullscreen          : true,
    controller          : 'DialogController'
});

Also, the script for the search.js controller is as follows:

(function() {

angular.module('myApp')
    .controller('DialogController', DialogController);

DialogController.$inject = ['$scope', '$mdDialog'];

function DialogController($scope, $mdDialog) {

    $scope.closeOpenedDialog  = closeOpenedDialog;

    function closeOpenedDialog() {
       $mdDialog.hide();
    }
}
})();

Answer №3

In the event that your mdDialog configuration is unable to identify your controller name due to it being in an external file, avoid using this method:

controller          : 'DialogController'

Instead, consider loading your controller as a directive within your dialog's view:

<md-dialog ng-controller="DialogController">
...
</md-dialog>

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

Error message: Metro bundler is unable to access the properties of an undefined object (specifically, 'transformFile')

Having encountered a problem after updating my project to expo SDK 43, I have experimented with different LTS node versions (14.8.1, 16.1.3, and 17.0.1) without success. Interestingly, my colleagues using Macs with Intel chipsets do not face this issue, le ...

The AngularJS price slider may exceed its range if the ng-model is null or below the minimum value

I currently have an rz-slider featured on my webpage that is utilized for gathering the price of a product from the user. In addition to the slider, there are two input fields present which are designated for storing the minimum and maximum values. The ng- ...

Is it possible to declare a variable as both $rootScope and $scope within the same controller?

Is it possible to declare a variable as both $rootScope and $scope in the same controller? $scope.Account=[{'sdfdsf','sdfds'}]; $scope.refreshAccountSummary = function () { Report.account(function (res) { $rootScope.Account ...

What steps do I need to take in order to generate a legitimate link annotation within Adobe Acrobat by utilizing Acrobat

Seeking guidance on how to embed an Acrobat Javascript within Adobe Acrobat in order to generate a link annotation. The current method involves using the "addLink" function within the document object, which triggers a Javascript action upon clicking the li ...

Error encountered during Ajax request - two files being transmitted instead of one

Can someone assist me with a basic ajax call for a login button? I need help with the form submission and sending the request to a php file to handle the login action. However, I am encountering an issue where two files are being sent instead of one when ...

Guide on transferring data from a JSON file to a JavaScript array

Currently, I am manually declaring the countries list for my typeahead search. To streamline this process, I want to retrieve the data from an external JSON file named countries.json. Here is a snippet of what the JSON file contains: [ { "id": ...

Utilizing a React component for interactive button functionality

In my React app, I decided to enhance my buttons by incorporating images using SVG. After discovering that I needed a separate component for my SVG files, I came across this helpful resource and created my own <SVGIcon /> component. However, when at ...

Troubleshooting: Issues with Jquery's replaceWith function

I'm facing an issue with a table I have that includes a button in one of its columns. The button is supposed to toggle the class of the current row in the table and then replace itself once clicked. $(document).ready(function() { $(".checkOut"). ...

Assigning information to a button within a cell from a dynamically generated row in a table

I've been diligently searching through numerous code samples but have yet to find a solution to my current dilemma: My HTML table is dynamically generated based on mustache values and follows this structure: <tbody> {{#Resul ...

Replace a certain substring with the corresponding keys found in an object using JavaScript

I am currently working on a function within a project that is designed to replace instances of /endpoint/{item.id}/disable/{item.name} with /endpoint/123/disable/lorem when the function is provided with the URL and item details. The item is expected to co ...

execute numerous Jssor Caption instances simultaneously

I have a Jssor slider and I want to create an animation for the first slide. My goal is to make two images come from the sides and merge in the center. I tried using a div for each image with a caption, and it works well. However, the second image starts ...

Vue component input form not providing expected result

Here is the code snippet for my "ecedata" component with an input field: <template> <div class="col-l-4"> <p style="text-align: center">Data/day (GB)</p> <div class="form-input-set" style="background: white"& ...

Ensure that all of the text boxes are aligned perfectly in the same vertical position

Is there a way to align all the textboxes in the same vertical position without using tables, only using HTML and CSS? The textboxes should start just after the label and follow the width of the label. Also, all labels are left-justified. Code :: <d ...

Customize Bootstrap radio buttons to resemble standard buttons with added form validation styling

Is there a way to style radio buttons to look like normal buttons while maintaining their functionality and form validation? I have two radio buttons that need styling but should still behave like radio buttons. Additionally, I am utilizing Bootstrap for s ...

Having trouble with the "foreach" binding in knockout where the "html" binding buttons are not functioning properly in Javascript

I'm experiencing an issue with the following code: <html lang="en"> <head> <link href="css/bootstrap.min.css" rel="stylesheet"> </head> <body> <script type='text/javascript' src='knockout-3. ...

Incorporating jQuery functions in the Angular app's main component file, app

I've been working on an Angular application and recently added the jQuery package with the following code: $ npm install jquery --save Now, I am attempting to transfer data from my HTML web page's .js file to the app.component.ts in Angular. I ...

Utilizing AngularJS to showcase nested JSON information

I am in the process of developing a versatile app that works seamlessly across different platforms using Onsen UI, Monaca, and AngularJS. One of the features I am working on involves enabling users to choose from a variety of switches using Onsen UI' ...

``From transitioning from Django templating to implementing a full RESTful architecture?

Looking to convert my django/html/css website to a REST (json) structure. Previously reliant on django template rendering for frontend responses. Interested in how to manage url redirection and incorporate json data into html templates without the use of ...

Is there a way to access Prestashop's Web service using a client's login credentials instead of a key?

Currently, I am delving into Prestashop's development and experimenting with creating a third-party application using react.js (specifically React Native). My goal is to retrieve Json data from the Prestashop webservice. However, my main focus is on a ...

Updating the subject line in Outlook emails

Can you change the subject of an email that someone receives in Outlook? I believe it might be possible. Perhaps similar to how user agents are used for browsers? I'm fairly new to emails and my online searches have not been helpful despite spending ...