Giter Site home page Giter Site logo

angular-modal-service's Introduction

angular-modal-service

CircleCI codecov Dependencies Dev Dependencies Greenkeeper badge GuardRails badge

Modal service for AngularJS - supports creating popups and modals via a service. Full support for Angular 1.5+ components. See a quick fiddle or a full set of samples at dwmkerr.github.io/angular-modal-service.

Usage

Install with Bower (or NPM):

bower install angular-modal-service
# or...
npm install angular-modal-service

Then reference the minified script:

<script src="bower_components/angular-modal-service/dst/angular-modal-service.min.js"></script>

Specify the modal service as a dependency of your application:

var app = angular.module('sampleapp', ['angularModalService']);

Now just inject the modal service into any controller, service or directive where you need it.

app.controller('SampleController', ["$scope", "ModalService", function($scope, ModalService) {

  $scope.showAModal = function() {

  	// Just provide a template url, a controller and call 'showModal'.
    ModalService.showModal({
      templateUrl: "yesno/yesno.html",
      controller: "YesNoController"
    }).then(function(modal) {
      // The modal object has the element built, if this is a bootstrap modal
      // you can call 'modal' to show it, if it's a custom modal just show or hide
      // it as you need to.
      modal.element.modal();
      modal.close.then(function(result) {
        $scope.message = result ? "You said Yes" : "You said No";
      });
    });

  };

}]);

Calling showModal returns a promise which is resolved when the modal DOM element is created and the controller for it is created. The promise returns a modal object which contains the element created, the controller, the scope and two promises: close and closed. Both are resolved to the result of the modal close function, but close is resolved as soon as the modal close function is called, while closed is only resolved once the modal has finished animating and has been completely removed from the DOM.

The modal controller can be any controller that you like, just remember that it is always provided with one extra parameter - the close function. Here's an example controller for a bootstrap modal:

app.controller('SampleModalController', function($scope, close) {

 $scope.dismissModal = function(result) {
 	close(result, 200); // close, but give 200ms for bootstrap to animate
 };

});

The close function is automatically injected to the modal controller and takes the result object (which is passed to the close and closed promises used by the caller). It can take an optional second parameter, the number of milliseconds to wait before destroying the DOM element. This is so that you can have a delay before destroying the DOM element if you are animating the closure. See Global Config for setting a default delay.

Now just make sure the close function is called by your modal controller when the modal should be closed and that's it. Quick hint - if you are using Bootstrap for your modals, then make sure the modal template only contains one root level element, see the FAQ for the gritty details of why.

To pass data into the modal controller, use the inputs field of the modal options. For example:

ModalService.showModal({
  templateUrl: "exampletemplate.html",
  controller: "ExampleController",
  inputs: {
    name: "Fry",
    year: 3001
  }
})

injects the name and year values into the controller:

app.controller('ExampleController', function($scope, name, year, close) {
});

You can also provide a controller function directly to the modal, with or without the controllerAs attribute. But if you provide controller attribute with as syntax and controllerAs attribute together, controllerAs will have high priority.

ModalService.showModal({
  template: "<div>Fry lives in {{futurama.city}}</div>",
  controller: function() {
    this.city = "New New York";
  },
  controllerAs : "futurama"
})

Support for AngularJS 1.5.x Components

It's also possible to specify a component, rather than a template and controller. This can be done by providing a component and an optional bindings value to the showModal function.

ModalService.showModal({
  component: 'myComponent',
  bindings: {
    name: 'Foo',
    myRecord: { id: '123' }
  }
})

ShowModal Options

The showModal function takes an object with these fields:

  • controller: The name of the controller to create. It could be a function.
  • controllerAs : The name of the variable on the scope instance of the controller is assigned to - (optional).
  • templateUrl: The URL of the HTML template to use for the modal.
  • template: If templateUrl is not specified, you can specify template as raw HTML for the modal.
  • inputs: A set of values to pass as inputs to the controller. Each value provided is injected into the controller constructor.
  • component: Renders a modal with the provided component as its template
  • bindings: Optional. If component is provided, all properties in bindings will be bound to the rendered component.
  • appendElement: The custom angular element or selector (such as #element-id) to append the modal to instead of default body element.
  • scope: Optional. If provided, the modal controller will use a new scope as a child of scope (created by calling scope.$new()) rather than a new scope created as a child of $rootScope.
  • bodyClass: Optional. The custom css class to append to the body while the modal is open (optional, useful when not using Bootstrap).
  • preClose: Optional. A function which will be called before the process of closing a modal starts. The signature is function preClose(modal, result, delay). It is provided the modal object, the result which was passed to close and the delay which was passed to close.
  • locationChangeSuccess: Optional. Allows the closing of the modal when the location changes to be configured. If no value is set, the modal is closed immediately when the $locationChangeSuccess event fires. If false is set, event is not fired. If a number n is set, then the event fires after n milliseconds.

The Modal Object

The modal object returned by showModal has this structure:

  • modal.element - The created DOM element. This is a jquery lite object (or jquery if full jquery is used). If you are using a bootstrap modal, you can call modal on this object to show the modal.
  • modal.scope - The new scope created for the modal DOM and controller.
  • modal.controller - The new controller created for the modal.
  • modal.close - A promise which is resolved when the modal close function is called.
  • modal.closed - A promise which is resolved once the modal has finished animating out of the DOM.

The Modal Controller

The controller that is used for the modal always has one extra parameter injected, a function called close. Call this function with any parameter (the result). This result parameter is then passed as the parameter of the close and closed promises used by the caller.

Closing All Modals

Sometimes you may way to forcibly close all open modals, for example if you are going to transition routes. You can use the ModalService.closeModals function for this:

ModalService.closeModals(optionalResult, optionalDelay);

The optionalResult parameter is pased into all close promises, the optionalDelay parameter has the same effect as the controller close function delay parameter.

Animation

ModalService cooperates with Angular's $animate service to allow easy implementation of custom animation. Specifically, showModal will trigger the ng-enter hook, and calling close will trigger the ng-leave hook. For example, if the ngAnimate module is installed, the following CSS rules will add fade in/fade out animations to a modal with the class modal:

.modal.ng-enter {
  transition: opacity .5s ease-out;
  opacity: 0;
}
.modal.ng-enter.ng-enter-active {
  opacity: 1;
}
.modal.ng-leave {
  transition: opacity .5s ease-out;
  opacity: 1;
}
.modal.ng-leave.ng-leave-active {
  opacity: 0;
}

Error Handing

As the ModalService exposes only one function, showModal, error handling is always performed in the same way. The showModal function returns a promise - if any part of the process fails, the promise will be rejected, meaning that a promise error handling function or catch function can be used to get the error details:

ModalService.showModal({
  templateUrl: "some/template.html",
  controller: "SomeController"
}).then(function(modal) {
  // only called on success...
}).catch(function(error) {
  // error contains a detailed error message.
  console.log(error);
});

Global Options Configuration

To configure the default options that will apply to all modals call configureOptions on the ModalServiceProvider.

app.config(["ModalServiceProvider", function(ModalServiceProvider) {

  ModalServiceProvider.configureOptions({closeDelay:500});

}]);

Here are the available global options:

  • closeDelay - This sets the default number of milliseconds to use in the close handler. This delay will also be used in the closeModals method and as the default for locationChangeSuccess.

Developing

To work with the code, just run:

npm install
npm test
npm start

The dependencies will install, the tests will be run (always a useful sanity check after a clean checkout) and the code will run. You can open the browser at localhost:8080 to see the samples. As you change the code in the src/ folder, it will be re-built and the browser will be updated.

The easiest way to adapt the code is to play with some of the examples in the samples folder.

Tests

Run tests with:

npm test

A coverage report is written to build\coverage.

Debug tests with:

npm run test-debug

This will run the tests in Chrome, allowing you to debug.

Releasing

To create a release:

  • Create the dst pack with npm run build
  • Merge your work to master
  • Use npm run release to tag, bump the version numbers and update the changelog
  • Push and deploy git push --follow-tags && npm publish

FAQ

Having problems? Check this FAQ first.

I'm using a Bootstrap Modal and the backdrop doesn't fade away

This can happen if your modal template contains more than one top level element. Imagine this case:

<!-- Some comment -->
<div>...some modal</div>

When you create the modal, the Angular Modal Service will add both of these elements to the page, then pass the elements to you as a jQuery selector. When you call bootstrap's modal function on it, like this:

modal.element.modal();

It will try and make both elements into a modal. This means both elements will get a backdrop. In this case, either remove the extra elements, or find the specific element you need from the provided modal.element property.

The backdrop STILL does not fade away after I call close OR I don't want to use the 'data-dismiss' attribute on a button, how can I close a modal manually?

You can check the 'Complex' sample (complexcontroller.js). The 'Cancel' button closes without using the data-dismiss attribute. In this case, just use the preClose option to ensure the bootstrap modal is removed:

ModalService.showModal({
  templateUrl: "some/bootstrap-template.html",
  controller: "SomeController",
  preClose: (modal) => { modal.element.modal('hide'); }
}).then(function(modal) {
  // etc
});

Another option is to grab the modal element in your controller, then call the bootstrap modal function to manually close the modal. Then call the close function as normal:

app.controller('ExampleModalController', [
  '$scope', '$element', 'close',
  function($scope, $element, close) {

  $scope.closeModal = function() {

    //  Manually hide the modal using bootstrap.
    $element.modal('hide');

    //  Now close as normal, but give 500ms for bootstrap to animate
    close(null, 500);
  };

}]);

I'm using a Bootstrap Modal and the dialog doesn't show up

Code is entered exactly as shown the example but when the showAModal() function fires the modal template html is appended to the body while the console outputs:

TypeError: undefined is not a function

Pointing to the code: modal.element.modal();. This occurs if you are using a Bootstap modal but have not included the Bootstrap JavaScript. The recommendation is to include the modal JavaScript before AngularJS.

How can I prevent a Bootstrap modal from being closed?

If you are using a bootstrap modal and want to make sure that only the close function will close the modal (not a click outside or escape), use the following attributes:

<div class="modal" data-backdrop="static" data-keyboard="false">

To do this programatically, use:

ModalService.showModal({
  templateUrl: "whatever.html",
  controller: "WhateverController"
}).then(function(modal) {
  modal.element.modal({
    backdrop: 'static',
    keyboard: false
  });
  modal.close.then(function(result) {
    //  ...etc
  });
});

Thanks lindamarieb and ledgeJumper!

Problems with Nested Modals

If you are trying to nest Bootstrap modals, you will run into issues. From Bootstrap:

Bootstrap only supports one modal window at a time. Nested modals aren’t supported as we believe them to be poor user experiences.

See: https://v4-alpha.getbootstrap.com/components/modal/#how-it-works

Some people have been able to get them working (see #176). Unfortunately, due to the lack of support in Bootstrap is has proven troublesome to support this in angular-modal-service.

Thanks

Thanks go the the following contributors:

  • DougKeller - Adding support for Angular 1.5 components.
  • joshvillbrandt - Adding support for $templateCache.
  • cointilt - Allowing the modal to be added to a custom element, not just the body.
  • kernowjoe - controllerAs
  • poporul - Improving the core logic around compilation and inputs.
  • jonasnas - Fixing template cache logic.
  • maxdow - Added support for controller inlining.
  • kernowjoe - Robustness around locationChange
  • arthur-xavier - Robustness when body element changes.
  • stormpooper - The new bodyClass feature.
  • decherneyge - Provider features, global configuration, appendElement improvements.

angular-modal-service's People

Contributors

ajoslin103 avatar akang avatar arthurxavierx avatar atefbb avatar cointilt avatar decherneyge avatar dougkeller avatar dryflyryan avatar dwmkerr avatar frknbasaran avatar greenkeeper[bot] avatar guardrails[bot] avatar joshvillbrandt avatar lexi-lambda avatar mattdesl avatar matteobarone avatar matuella avatar maxdow avatar nakamurabh avatar poporul avatar rumkin avatar samwx avatar smalbs avatar stormpooper avatar swbanks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-modal-service's Issues

Doesn't work well when using router

I am calling ModalService from a directive, which works well when on a particular route view. However, when I change the route to other view where the same directive exists, the ModelService fails to open.
Another issue I observed, when using ModalService in another service and called from any controller, again fails to open.

Can't always close modal window

I am getting this message "Scripts may close only the windows that were opened by it.", and I can only use the "Cancel" button to close a window. As far as I can tell I am set up exactly as it is in the sample. Even when I use the cancel button, I get the same message but the window does close. Strange...

modal() is undefined and modal template is appended to body

Code is entered exactly as the example and when the showAModal() function fires the modal template html is appended to the body while the console outputs this:

TypeError: undefined is not a functionwhich points to this line modal.element.modal();

Using Angular 1.3.0
Any insight is appreciated.

Code in the controller

            $scope.showAModal = function () {
                ModalService.showModal({
                    templateUrl: 'partials/cancel-membership.modal.html',
                    controller: 'ModalCtrl'
                }).then(function (modal) {

                    //it's a bootstrap element, use 'modal' to show it
                    modal.element.modal();
                    modal.close.then(function (result) {
                        console.log(result);
                    });
                });
            };

Modal $scope

I'm running into an issue with a modal's $scope. It looks like the modal's $scope is set to rootscope. I'm trying to use $emit to send an event from within the modal and the listener in my AppController never receives it. AppController is attached to the body.

What is the best way to handle this?

Compatibility issue with angular-google-places-autocomplete

Hi, I would like to create a modal view with an input suggesting places from google maps api.
Previously to do that I used the angular-google-places-autocomplete library (https://github.com/kuhnza/angular-google-places-autocomplete/), but now when I try to integrate it with the modal it does not work.

What I did is to modify the angularModularService in this way:

var module = angular.module('angularModalService', ['google.places']);

but it didn't worked.

Jquery dependency

Hi Dave,
Excellent tutorial on reusable modal windows.
However I've found some issues in your project.

  1. You said there are no dependencies however if I try to remove JQuery it is showing an error "TypeError: Cannot set property 'display' of undefined" -> How to resolve this?
  2. While displaying custom modal window, styling (CSS) of custom modal window is appearing in background -> Whats happening and how to resolve this?
    custommodalwindow
    It would be great if you could look into this and resolve the same.

How do I remove the element?

In FAQ "I'm using a Bootstrap Modal and the backdrop doesn't fade away", it mentions: "It will try and make both elements into a modal. This means both elements will get a backdrop. In this case, either remove the extra elements, or find the specific element you need from the provided modal.element property."

I have a scenario where I want to force the user to take an action via a modal dialog. If the user does not take the action and reloads the page, it will open the dialog again with the result that the dialog cannot be closed properly.

How do I find the existing dialog element and remove it?

Howto test the ModalController ?

Hi can you help me writing unit test for modal controllers ?

I tried but I'm not able to solve these errors:

  • Error: [$injector:unpr] Unknown provider: $elementProvider <- $element <- PartsEditmenudialogctrlCtrl
    Or
  • Error: [$injector:unpr] Unknown provider: closeProvider <- close <- PartsEditmenudialogctrlCtrl

PLease, can you add a controller test to your complexcontroller example ?

My interesting part of the test code is:

beforeEach(inject(function ($controller, $rootScope) {    
    scope = $rootScope.$new();
    PartsEditmenudialogctrlCtrl = $controller('PartsEditmenudialogctrlCtrl', {
      $scope: scope
    });

and for the controller

.controller('PartsEditmenudialogctrlCtrl', [ '$route', '$scope' , '$log', 'growl', 'MainMenuService', '$element', 'close', 'currMainMenuEditData', 
                                               function ($route, $scope, $log, growl, MainMenuService, $element, close, currMainMenuEditData) {

Thanks in advance
Stefano

Publish 0.6.6 onto NPM

The latest tag (0.6.6) isn't on NPM which includes the IE8 fix. Could someone publish it there?

Optional controller

Why controller option is required for showModal? Maybe make it optional for modals without controllers.

Is there a Bootstrap version dependency?

I cannot get this to work with the latest bootstrap CSS (v.3.3.4): The modal appears but remains somewhat faded and there is not control over it. It disappears with any click.
On the other hand when using the bootstrap CSS provided in the example code, everything is fine!

Any insight on this behavior?

Passing a controller constructor

In the current system, and if i understand it, to use a custom modal, you have to pass a controller already created :

app.controler("SomeController", function($scope, close) {
 $scope.dismissModal = function(result) {
    close(result, 200); 
 };
});
ModalService.showModal({
  templateUrl: "some/template.html",
  controller: "SomeController"
});

I can't find a way to do this without changing the code :

ModalService.showModal({
  templateUrl: "some/template.html",
  controller: function($scope, close) {
      $scope.dismissModal = function(result) {
         close(result, 200); 
      };
  }
});

Do you plan to add this feature ?

Bootstrap modal templates sometimes cause duplicate modal backdrops

I was using a template for my model that had the following root element:

<div class="modal fade">
 nested content
</div>

If my template included ANYTHING after the closing </div>, including comments, the modal spawned one additional <div class="modal-backdrop in"></div> per element. In testing,

In testing, I tried adding <div></div> after the closing div and TWO of the above extra backdrop classes were added.

The issue with the extra modal-backdrop classes is that they don't get removed from the DOM when the modal is closed, and so the user cannot interact with the UI any longer without refreshing, and of course, if there are any visual styles applied to the backdrop, such as the popular opacity effect, those too remain after closing the modal.

This may not be a problem with the angular-modal-service code, perhaps it is, or perhaps the jQuery selector is overly ambitious? I will look into it further, but post this here in case anyone else runs into this sneaky problem since comments following div tags are commonplace.

How can i set the modal backdrop static?

Hello,

I am testing the modals and I don't know how to set backdrop to static like the boostrap modal.

Ej: ModalService.showModal({
templateUrl: "complex/complex.html",
controller: "ComplexController",
backdrop: 'static', <===================== here
inputs: {
title: "A More Complex Example"
}
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {
$scope.complexResult = "Name: " + result.name + ", age: " + result.age;
});
});

Thanks in advance.

No examples for using appendElement?

Hi,

I'd like to see an example for using the appendElement in the call to showModal(). Could you add it to the examples? :-)

Cheers,
Allister

Associate EnterKey to default button like ok

I have the following form. i want to preceed with Ok action when enter key is pressed, but cannot get it to work. I have tried various option including jquery but non of it works.
How can i associate Enter Key to certain button like OK.

<div id="modalDialog" class="modal-dialog">
<div class="modal-header">
    <h2 style="text-align: center">{{modalOptions.headerText}}</h2>
</div>
<div class="modal-body">
    <p>{{modalOptions.bodyText}}</p>
</div>
<div class="modal-footer">
    <button type="button" class="btn" data-ng-click="modalOptions.close()">     {{modalOptions.closeButtonText}}</button>
    <button type="button" id="OK" class="btn btn-danger" ng-enter="modalOptions.ok();" autofocus data-ng-click="modalOptions.ok();" data-ng-keyup="$event.keycode == 13 && modaloptions.ok()">{{modalOptions.actionButtonText}}</button>
</div>
<script type="text/javascript"> $(document).ready(function () { console.log('Modal Template Loaded'); $('#OK').focus();
       $("#modalDialog").keydown(function (event) {
           console.log("Event mapped")
           if (event.keyCode == 13) {
               $(this).parent()
                      .find("button:eq(0)").trigger("click");
               return false;
           }
       });

   }); //document

</script>`

Controller of the dialog should be called before the template directives' links

Your article clearly show an execution order:

var modalController = $controller(controller, inputs);  
var modalElementTemplate = angular.element(template);  
var linkFn = $compile(modalElementTemplate);  
var modalElement = linkFn(modalScope);  

which is confirmed by other - articles.
So far, so good... The code of your service, up to version 0.2.0, was doing that.

Commit bca78f1 broke that, wanting to allow injecting $element into the controller, so calling the controller after the link of directives in the template have been called.

This is apparently a violation of a fundamental rule of AngularJS, for a minor, not so much used feature... πŸ˜„

This bites me because I have a directive (from angular-selectize) which takes configuration data at link time, and then creates an instance of Selectize with this configuration. So, it is not a real double-binding and it cannot catch-up the configuration created too late when the controller is ran.

I imagine we can have similar issues with one-time binding (the new 1.3's :: annotation).

Honestly, I have no idea if there is a way to maintain the injection of $element while restoring the proper init order... At worst, you can add an option to the showModal() parameter object, telling $element must be injected, and thus calling the controller later.

Note: I use AngularJS 1.3.15.

Angular 1.3

Currently the bower.json limits this module to the 1.2.x line. I have been testing it on 1.3.0-rc.4 for a while this morning and have not found any compatibility issues.

More of an informational than an issue, but hopefully useful information as this moves forward.

keyboard events are directed to background page

When a modal is open, and the page behind it is obscured

While you cannot click on anything on that page

You can still tab to move the tab-focus around on the page -- and hit spacebar/enter to trigger the highlighted item

Proper modal cleanup with Bootstrap

I looked through the examples to see if there was already a documented way of properly cleaning up a modal that is dismissed when clicking outside the modal area. I didn't see anything and noticed there were many ng-click directives used to catch the modal closing.

Instead of attaching ng-click directives to all the elements and faking the animation time for the modal to disappear I used the events generated by bootstrap. I inserted this at the top of my controller to make sure the modal is properly cleaned up regardless of how it is closed and waits for the animation to finish. This handles clicking outside the modal to close, data-dismiss="modal", and $element.modal('hide').

$element.on('hidden.bs.modal', close)

I thought this might be useful documentation in the FAQ.

prevent close

hi, I want to decide when I close the modal, and that it is only the close button to close the modal, you can .

thank you

Massimo

Getting an error: looking up elements via selectors is not supported

Bootstrap dependency?

Hi,

thanks a lot for your this nice utitilty.

One question: What is the reason behind including a dependency to bootstrap in your bower.json? I actually don't see the need for this except the samples. I am using bootstrap-sass and as all bower dependencies get auto injected during the build of my project, I end up with 2 bootstrap versions.

Any suggestions? Much appreciated ;)

Cheers!

Passing data to the model?

Hi ,

I want to pass the message to display in the model window? Do you have any samples of that? please let me know.

Why is my modal dialog leaving shadow behind?

I followed the sample code and it is kind of working, except that the then() function doesn't get called when I dismiss the dialog. I'm not sure if this is related to the fact I'm also using AngularStrap in the project.

updateModal needed for transitions

Take your example:

ModalService.showModal({
  templateUrl: "some/template.html",
  controller: "SomeController"
}).then(function(modal) {
  // only called on success...
}).catch(function(error) {
  // error contains a detailed error message.
  console.log(error);
});

I would be nice to keep the modal open and update it. So, in the error handler, do something like this:

ModalService.showModal({
  templateUrl: "some/template.html",
  controller: "SomeController"
}).then(function(modal) {
  // only called on success...
}).catch(function(error) {
  ModalService.updateModal({
  templateUrl: "error/template.html",
  controller: "errorController"
}).then(function(modal) {
  modal.element.modal()
})
});

Unit testing

Thank you for this great addition to angular, I love the flexibility and ease of use.

I am trying to write unit tests for a controller I'm using in a modal and cannot figure out how to inject the close provider into my tests since it looks like there's some angular magic going on. Any tips to help?

it('should implement close()', function () {
      inject(function ($controller, $rootScope) {
        var scope;

        scope = $rootScope.$new();
        $controller('TemplateController', { $scope: scope } );

        expect(angular.isFunction(scope.close)).toBeTruthy();
      });
    }); // should implement close()

The controller is as simple as:

TimelineControllers.controller('TemplateController', ['$scope', 'close', function($scope, close) {
    $scope.close = function () {
      close('i was closed');
    };
  }]);

Publish to npm

@dwmkerr, it'd be really great if you can publish this to npm. Since you already have package.json, it is really easy. Here are the simple steps:

  1. cd to your local repo
  2. npm adduser (and enter your info/creds (don't worry if you don't have an account)... these are the same info/creds that will log you in to npmjs.com)
  3. npm publish

That's it! πŸ˜„
Demo video: https://docs.npmjs.com/getting-started/publishing-npm-packages

Need API to Close Modals

See comment at:

http://www.dwmkerr.com/the-only-angularjs-modal-service-youll-ever-need/#comment-1810738299

It would be useful to have an API such as:

modalService.closeModals();

which simply closes any open modals. A potential use case is in the application router, where changing a URL should not leave the modal open. Even better would be:

modalService.closeModals(someValue);

Which would close all the modals and resolve their close promises with the value someValue. This would allow application developers to decide whether they want to allow consumers of modals to be able to handle the cases where they are closed externally explicitly.

Sample for custom save button

Hi, is it possible to attach a sample with a 'save' button and showing where is the best place to call the save(record) methode and how to react on a cancel to restore the old values?

many thanks

Unknown provider: closeProvider <- close

Oddly enough, I've used angular-modal-service successfully in other projects, but haven't been able to pinpoint why this project is special. I'm not using bootstrap in any of the projects.

I'm getting this error using 0.3-0.5

Controller:

    .controller('SettingsCtrl', ['$scope', 'close', function ($scope, close) {
        $scope.close = function(result) {
            close(true);
        };

        $scope.cancel = function() {
            close();
        };
    }])

Launch point:

angular.module('settings',
    [
        'angularModalService'
    ])
.controller('CoreCtrl', ['$scope', '$window', 'ModalService',  function($scope, $window, ModalService){
        $scope.openSettingsDialog = function() {
            ModalService.showModal({
                templateUrl: 'markup/settings.html',
                controller: 'SettingsCtrl'
            }).then(function(modal){
                modal.close.then(function(result) {

                });
            });
        };
}])

Add support for $templateCache

Some build methods preload templates into the template cache. Because of this, templates may never be available directly at their specified URL, so always using $http to get a template might fail.

$templateCache docs

scroll vanishes after close

Hi,

I am using a $timeout to automatically close a modal after 1000 milliseconds. But the scroll bar does not come back into action after this. If I close by clicking on the close button (or anywhere other than the modal) then the scroll bar comes back fine. I have tested this on safari and firefox (on OS X).

I am using the following controller:

app.controller('YesNoController', ['$scope', 'title', 'close', '$timeout', function($scope, title, close, $timeout) {

$scope.title = title;

$timeout( function(){ 
    close('yes', 500); // close, but give 500ms for bootstrap to animate
}, 1000);

$scope.close = function(result) {
close(result, 500); // close, but give 500ms for bootstrap to animate
};

}]);

.modal-open still attached to body after modal is closed

Everytime I open a modal, .modal-open is still attached to the body of my page.
The overflow: hiddden property prevent me to slide my page after a modal is opened.

View:

<div class="modal fade">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" ng-click="close(false)" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">{{params.title || 'Are you sure ?'}}</h4>
      </div>
      <div class="modal-body">
        <p>
          {{params.text || 'Really ?'}}
        </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-white" ng-click="close(false)" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" ng-click="close(true)" data-dismiss="modal">Save changes</button>
      </div>
    </div>
  </div>
</div>

Controller:

angular.module('app')
  .controller('ConfirmModalCtrl', function ($scope, close, params) {
    $scope.params = params;

    $scope.close = function(res) {
      close(res, 200);
    };
  });

Call:

ModalService.showModal({
        templateUrl: 'views/modals/confirm.modal.view.html',
        controller: 'ConfirmModalCtrl',
        inputs: {
          params: {
            title: 'Are you sure ?',
            text: '... bla bla bla'
          }
        }
      }).then(function(modal) {
        modal.element.modal();
        modal.close.then(function(res) {
           console.log(res);
        });
      });

I have seriously no idea where it could come from.
I've already checked all dependencies and they are fine (bootstrap, angular, ModalService)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.