What is the best way to summon a modal service in an application using a route provider?

After exploring numerous tutorials on creating basic modals using angular bootstrap, I've noticed that most examples are geared towards single-page applications without the use of route provider or more intricate architectural patterns. What specific modifications are required in this Plnkr code to allow a modal service to be invoked through a controller in an application utilizing route provider?

The mentioned example in the provided plnkr demonstrates an application with:
1.) a route provider featuring two routes, / and /public1.
2.) A navigation controller managing the table of contents positioned above one or both routes.
3.) Injection of a modalService into the navigation controller.
4.) The presence of a div in index.html containing the table of contents controlled by the navigation controller. A button within this navigation div invokes the deleteCustomer() method of the controller which should trigger the appearance of a modal. What alterations need to be implemented for the modal to display upon clicking the button?

Upon attempting to launch the app, my FireFox debugger on the devbox logs the following error:

Error: [$injector:modulerr] Failed to instantiate module hello due to:
[$injector:modulerr] Failed to instantiate module navigation due to:
[$injector:modulerr] Failed to instantiate module modalService due to:
[$injector:nomod] Module 'modalService' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.5.0/$injector/nomod?p0=modalService
minErr/<@http://localhost:9000/bower_components/angular/angular.js:68:12
module/<@http://localhost:9000/bower_components/angular/angular.js:2015:1
ensure@http://localhost:9000/bower_components/angular/angular.js:1939:38
module@http://localhost:9000/bower_components/angular/angular.js:2013:1
loadModules/<@http://localhost:9000/bower_components/angular/angular.js:4503:22
forEach@http://localhost:9000/bower_components/angular/angular.js:321:11
loadModules@http://localhost:9000/bower_components/angular/angular.js:4

When downloading the Plnkr source as a zip file, then extracting and debugging in the local browser, the FireFox debugger indicates failure to instantiate the hello module—core to the Plnkr app. Once we resolve the simple issue of loading the main module of the app, recreating the problem within the Plnkr app should be straightforward. (Guidance on resolving this would be greatly appreciated).


THE CODE:


Although the complete code is available in the linked Plnkr, excerpts are presented below:

index.html snippet:

<!DOCTYPE html>
<html>

  <head>
    <base href="/" />
    <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c2de9ad5d8d8c3c4c3c5d6c7f7879986849986">[email protected]</a>" data-semver="0.13.1" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9bca0e4aba6a6bdbabdbba8b989f9e7f8fae7f8">[email protected]</a>" data-semver="0.13.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.1/ui-bootstrap.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js" data-semver="1.5.0" data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1c131a08111c0f170e3d4c5348534d">[email protected]</a>"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="hello" ng-cloak class="ng-cloak">
    <!-- start of content section -->
    <h1>Hello Plunker!</h1>

    <div ng-controller="navigation" class="container">
        <ul class="nav nav-pills" role="tablist"  >
            <li><a class="label label-success" href="/">Home</a></li>
              <li><a class="label label-success" href="/public1">public1</a></li>
        </ul>
        <!-- modal test follows -->
            <p><a href class="btn btn-default btn-lg " ng-click="deleteCustomer()">Click to Delete Customer</a></p>
          <!-- end of modal test -->
    </div>

    <div class="container">
    <div ng-view=""></div>
    </div>

    <!-- end of content section -->    

    <!-- begin local build files -->
    <!-- <script src="script.js"></script> -->
    <script src="modalService.js"></script>
    <script src="home.js"></script>
    <script src="public1.js"></script>
    <script src="navigation.js"></script>
    <!-- end local build files -->

  </body>

</html>

script.js code snippet:

'use strict';

/** * Main module of the application. */
angular
  .module('hello', [
    'ngAnimate',
    'ngRoute',
    'ngTouch', 'home', 'public1', 'navigation' 
  ])
  .config(function ($routeProvider, $httpProvider, $locationProvider) {

    $locationProvider.html5Mode(true);

    $routeProvider
    .when('/', {
        templateUrl : 'home.html',
        controller : 'home',
        controllerAs: 'home'
    })
    .when('/public1', {
        templateUrl : 'public1.html',
        controller : 'public1',
        controllerAs: 'public1'
    })
    .otherwise('/');

    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

  })
.run([ function() {

}]);  

navigation.js excerpt:

'use strict';

angular
.module('navigation', ['modalService', 'ngRoute'])
.controller('navigation', function($scope, modalService, $route) {

    $scope.tab = function(route) {
        return $route.current && route === $route.current.controller;
    };

    $scope.deleteCustomer = function () {

        var custName = 'Some Random Person';

        var modalOptions = {
            closeButtonText: 'Cancel',
            actionButtonText: 'Delete Customer',
            headerText: 'Delete ' + custName + '?',
            bodyText: 'Are you sure you want to delete this customer?'
        };

        modalService.showModal({}, modalOptions).then(function (result) {
            //some code will go here.  But for now can we just
            //get the modal to appear and for the cancel button to work?
        });
    }

});

And modalService.js segment:

'use strict';

angular.module('modalService').service('modalService', ['$modal',
    function ($modal) {

        var modalDefaults = {
            backdrop: true,
            keyboard: true,
            modalFade: true,
            templateUrl: 'modalContent.html'
        };

        var modalOptions = {
            closeButtonText: 'Close',
            actionButtonText: 'OK',
            headerText: 'Proceed?',
            bodyText: 'Perform this action?'
        };

        this.showModal = function (customModalDefaults, customModalOptions) {
            if (!customModalDefaults) customModalDefaults = {};
            customModalDefaults.backdrop = 'static';
            return this.show(customModalDefaults, customModalOptions);
        };

        this.show = function (customModalDefaults, customModalOptions) {
            //Create temp objects to work with since we're in a singleton service
            var tempModalDefaults = {};
            var tempModalOptions = {};

            //Map angular-ui modal custom defaults to modal defaults defined in service
            angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);

            //Map modal.html $scope custom properties to defaults defined in service
            angular.extend(tempModalOptions, modalOptions, customModalOptions);

            if (!tempModalDefaults.controller) {
                tempModalDefaults.controller = function ($scope, $modalInstance) {
                    $scope.modalOptions = tempModalOptions;
                    $scope.modalOptions.ok = function (result) {
                        $modalInstance.close(result);
                    };
                    $scope.modalOptions.close = function (result) {
                        $modalInstance.dismiss('cancel');
                    };
                }
            }

            return $modal.open(tempModalDefaults).result;
        };

    }]);

Answer №1

Check out the code below for a solution:

If you're using Plunker, don't forget to configure <base href="/" /> like this:

<script>
    document.write('<base href="' + document.location + '" />');
</script>

Make sure you have included the necessary scripts for ui-bootstrap:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-touch.js"></script>

Also remember to load ui.bootstrap in your module:

angular.module('modalService', ['ui.bootstrap']).service('modalService', ['$modal', function(){...})

For more details and example, visit: http://plnkr.co/edit/4BiF2SlhOZDrFgMzj31z?p=preview

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

Storing cookies is not supported when using jQuery for authentication with Passport.JS

My software setup includes an Electron app for the frontend and a Node backend. After clicking the login button, the app sends an Ajax POST request to the backend, which confirms successful authentication. However, when checking if the user is authentica ...

How to Incorporate Routes as Subroutes in Express.js

I am currently working on constructing a modular express.js server with a well-organized structure. I have experimented with using routes similar to components in React. index.js var syncsingle = require('./XYZ/syncsingle'); app.get('/sync ...

The issue of v-bind:checked not functioning properly across all component instances

Presenting a unique radio list component: <template> <div class="list"> <div class="radio"> <input type="radio" name="custom-radio-list" :id="'custom-radio-full-' + cid" value="" @change="updateCustomRadio" ...

What is the best way to activate a watch upon clicking a button?

Is there a way to use the $watch() method on a button in order to trigger it when the button is pressed? Here is an example of the HTML: <button style="margin-left:10px;" class="btn btn-danger btn-xs"> Re-init tableau ...

Obtaining metadata from Youtube videos with Javascript and HTML5

Is there a way to fetch YouTube video data with Javascript and HTML5? If so, could you provide some helpful resources or links? ...

Wide container using Bootstrap

Currently, I am incorporating Bootstrap v5 alpha to develop a basic dashboard. According to Bootstrap guidelines, it is essential to utilize .container, .container-fluid, or .container-{size}, followed by .row and .col columns. However, I wish for the das ...

Using jQuery and Ajax to efficiently handle the retrieval of large files while browsing

I have some large text files that are potentially multiple GB in size, and I am looking for a way to view them within a div element. The idea is to make an AJAX request for a more manageable chunk of the file, have the AJAX script (preferably in PHP) inte ...

Troubleshooting why the Angular JS ng-if directive is not functioning properly with a boolean

When using ng-if with a flag and a list that contains values: <tr ng-if="flag" ng-repeat="x in list1"> {{"output a"}} <!-- perform some action --> </tr> <tr ng-if="!flag" ng-repeat="x in list2"> {{"output b"}} < ...

Changing from a vertical to horizontal menu as the parent div is resized

I am looking for a solution to create a CSS effect or Javascript code that will hide a menu inside a div when the browser window or parent div is resized. I want to display another div with the same menu in horizontal orientation when the first one is hidd ...

Error: The function Undefined is not recognized by express.io

Struggling to configure express.io with individual files for each route? Check out the examples provided. Currently, I have a typical Express setup that I want to transition to express.io: Project app.js routes servepage.js Views ...

The Ajax call failed to complete

As part of my project, I am creating a subscription form for newsletters. To integrate the form with the MailChimp API, I am utilizing an AJAX request. The API functions correctly when tested independently. However, I encountered an issue with the AJAX cod ...

The method of displaying milliseconds in a JavaScript countdown timer

I have a piece of javascript code that is responsible for showing a countdown timer starting from 5 minutes. Here is the code snippet: var mins var secs; function startCountdown() { mins = 1 * m("05"); // set the minutes here secs = 0 + s(":00") ...

Using Rails AJAX to dynamically load partials without the need to submit

Imagine creating a dynamic page layout with two interactive columns: | Design Your Pizza Form | Suggested Pizzas | As you customize your pizza using the form in the left column, the right column will start suggesting various types of pizzas based on your ...

I'm new to Bootstrap and I'm looking for a way to customize the functionality of table 1 compared to table

I am currently facing a unique issue for which I cannot find a solution. The problem lies in my timesheet table, where I intend to only add data to Table #1. However, whenever I click the + sign in the table, the same data is also displayed in Table #2. De ...

Storing information from a table into LocalStorage

$('.new_customer').click(function () { var table = $("table"); var number = table.find('tr').length; table.append('<tr id="' + number + '"><td><input type="button" class="btn btn-success btn-xs" ...

Secure access using Android and Node.js

Recently, I have been working on building an Android app with Node.js on the server and using PostgreSQL as the database. A few days back, I implemented a simple authentication feature on a website using Passport. Now, my goal is to maintain the session e ...

Node.js using Express: Modifying response data for specific route

I've searched through numerous resources but haven't been able to find a solution, so I'm reaching out for some assistance! :) I have developed a UI5 Application using Node.js with Express on the server-side. The data is retrieved from a SQ ...

The issue with MaterialUI Select's set value is that it consistently falls outside the expected

I'm currently working on a MaterialUI Select component where I am dynamically handling the value parameter. However, I'm facing an issue where even though I set a valid value from the available options, it always shows as out of range. SelectInp ...

Discover the simple steps for automatically scrolling to a specific div using AngularJS

I want the error message div to appear when I click on the submit button and I also want the screen to automatically scroll to that div. Below are my code snippets: CSS:- .error_msg { background: none repeat scroll 0 0 #F16200; border: 0 solid # ...

Ways to target only the adjacent div

My goal is to target only the next div with the class name indented. Each indented div should have the same id as the <li> element right before it. Currently, I want each div with the class name indented to have the id of the previous <li>. He ...