Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to handle modals in Angular JS?

Problem: How do I manage a bunch of modals in an Angular JS controller?

I was putting them at the bottom of my view and using http://angular-ui.github.io/bootstrap/#/modal but I was ending up with large html templates (that work) but feel inefficient.

What I've tried:

  • $dialog from UI-Bootstrap (pain in the butt)
  • Modals stored in templates included via ng-include using UI-Bootstrap's modal
  • modals put at the bottom of my view within the controller << currently on and is working

This feels like I'm missing something. Any pointers?

EDIT:

I did A LOT of searching and found a script and then upgraded it a bit:

  • Your modals are external templates
  • Their also in the scope where you clicked the button
  • 3 different kinds (Confirm, Message, Load a template)

https://github.com/clouddueling/angularjs-modals

Update

I've since made a repo covering this issue: http://clouddueling.github.io/angular-common/

like image 510
Michael J. Calkins Avatar asked May 23 '13 23:05

Michael J. Calkins


1 Answers

As rGil stated, use a directive, your own and not UI-Bootstrap if it seems too convoluted. All your modals will be similar, more or less. You just have to have a template and 2-3 scope variables to populate the modal. You can then pass parameters to open and close the modal as well and offer further functionality. The more you include the bigger the directive will be.

A second option would be to create separate HTML partials with those modals, and then just use ngInclude to place them in your views. This would be a huge time saver if your modals are different, but are reused frequently on multiple pages. Down sides to this is that you still need to toggle it open and closed. The Angular way would be to write a directive to handle just the toggling if that is all you need. The easy way is to write a little jQuery and open the modal on click or whatever.

Honestly, what it all comes down to is your comfort level. Will jQuery destroy your code? No, but it is not the "Angular Way". With jQuery, I can write a modal toggle in 3-4 lines of code. Doing it the Angular Way is a directive and a dozen+ lines of code. But the Angular way has the benefit of writing a tag in the future and no more code is needed. If I have just one modal, I may do it in jQuery. If I have multiple modals, as in your case, I may invest the time to learn directives and come up with one that works how I want it to work.

like image 72
Tim Withers Avatar answered Sep 20 '22 10:09

Tim Withers