What are Controllers?
Ionic uses AngularJS controllers to control the flow of data between the view and the business logic contained in the services. You can imagine the controller acting as a thin layer that connects the two together. I say thin because best practice dictates that most of the business logic should be contain in the services. I go into more detail on how the view, controller, and service interact below.
Main Controller
If you remember in step 1, we assigned mainCtrler to the ng-controller directive in the index.html. Then in step 3, we created an interceptor that dispatches an event when a user is unauthenticated. Now finally, we defined the controller mainCtrler to handle the Unauthenticated event using the $scope.on() to listen for the $broadcast() from the interceptor.

When an Unauthenticated event is received, the mainCtrler will change state to login and then direct the user to either enter their login or create a new account with a pop-up message box via $ionicPopup service.
The $ionicPopup is great for creating and showing popup messages to the users that require their attention. The user must respond to the popup before they may continue. There are 4 different methods of popups you can call in your app: custom, confirm, alert, and prompt. For our purpose the alert popup will suffice. It is a one button popup that shows a simple message that the user can tap to close. We want to notify the user that they must login or create an account before they can have access to the member only portion of the app.
Register Controller
When the a user registers an account by filling out the form in our register view and clicking the register button, the register controller calls the UserService.register function in our services.js file. It passes the user property of the $scope that was created via the ng-model directive in our template. Based on whether the account creation was successful or not, the appropriate popup message will appear to the user. Remember, our backend API returns JSON data with a success and text properties on both success and failure. If the account was created successfully, we direct the user to the login view with $state.go().

Login Controller
The login controller is very much similar to the register controller defined above. Our login view contains a simple form of two input boxes for the username and password. When the user clicks on the login button, the controller will call the UserService.login function with the $scope.user object. Upon success, the user will enter the member only area, otherwise the user will get a popup indicating an unsuccessful login.

Member Controller
The member only area is simple view. The view has a logout button which users can click to log themselves out of the app. When the user clicks the button, the controller calls the UserService.logout function which simply removes the token from the header, and sets IsAuth to false.
