Step 2. Creating Routes

Routing

The Ionic framework uses the UI-Router for navigation between states. We will now add and configure all the states we will be using in our app. We have three states in our app: login, register, and member-area. In the app.js file, add the following code:

routestates

Each of the three states has a url, templateUrl, and controller. The url is the URL route that is accessed by the href property. The templateUrl specifies the path of the view to be used with the state. These are the html files in our template folder that we created in step 1. Remember from the previous step, we added ng-click directives to our html files to called functions in our controllers. Here we specify the controller to be used with that particular view. The $stateProvider links a page or view with a controller.

After adding our states, we set the default route to the login view using $urlRouterProvider.otherwise method for instances where the app can not find a route matching the ones we’ve set.

Finally, we utilize .run method of our app to detect state changes with $stateChangeStart which triggers when changing routes or URL. On each route change, we check to see if the user is authenticated. If the user is not authenticated then we cancel the event with .preventDefault() and redirect the user to the login view with $state.go(). We made exceptions to the login and register state for unauthenticated users. You probably notice that we utilized a service to determine whether the user is authenticate. We will be writing our services in the next section.

routechangestate

<BACK | NEXT>