There are a number of ways to approach implementing modals in an AngularJS application, including the popular angular-dialog-service and the official Angular-UI Bootstrap modal. In this article I'll share how I like to handle modals in Angular, using another Angular-UI service, the ui-router.
Thinking in States
The core idea behind this approach is that modals are in fact unique states of your application. Consider an e-commerce site. When you click the "Add to cart" button, a modal pops up asking you to log in. You enter your details and click "Continue", which show's you another modal with the details of your cart.
You've just traversed a number of states that just happened to be in modals. If we think of modals as states, then it makes sense to use a state management tool to go to and from different modal states.
Getting Started with the UI Router
Let's keep it simple to start with. First, we'll install the ui-router and add it to our Angular app.
1. Create a Simple HTML Page
We'll start by creating an index.html file with the following contents:
[html] < !doctype html> [/html]
jQuery has been included for some DOM work later on.
In addition to including the latest version of Angular itself, I've included the Angular UI Router, a CSS file (currently empty), and of course our app's main JavaScript file. Let's take a look at that next.
2. Create Your Angular App
The app.js file is incredibly simple at this point. We just create a module for our modalApp and then add the ui.router as a dependency:
[js] angular.module("modalApp", ["ui.router"]) [/js]
3. Fleshing Out the Interface
Before we can open a modal, we need a UI for the user to interact with. In this instance I've kept things simple with an "Add to cart button" in index.html:
[html] < !doctype html>
Pusheen Hoodie
Now you too can look like Pusheen!
[/html]
4. Configure the Initial States
We're going to be defining a number of states for each of our modals, but there's a bit of setup we need to do first. Since it's likely that we'll want to share behavior between our different modals, let's create a parent Modal state that our individual modals can then inherit from. The following code belongs in js/app.js:
[js] angular.module("modalApp", ["ui.router"]).config(function($stateProvider) { $stateProvider.state("Modal", { views:{ "modal": { templateUrl: "modal.html" } }, abstract: true }); }); [/js]
Continue reading %Creating Stateful Modals in AngularJS with Angular UI Router%
by Brad Barrow via SitePoint
No comments:
Post a Comment