Angular Modal Window Example using $ Method

Angular Modal Window Example using $ Method

Create a modal window with a form to add users to our subscribers model. You will need a button which will launch the modal window when clicked. So create button in the app/views/subscribers.html as highlighted below:

<button class="btn btn-success" ng-click="showModal()"> Add New User</button>
<div class="gridStyles" ng-grid="gridOptions">

now create the partial for the modal view.

Create a new file called add-user.html within the app/views folder and let’s put in the markup for the Add User Form as follows:

<div class="modal-header">
<button type="button" class="close" ng-click="cancel()" datadismiss="modal" aria-hidden="true">&times;</button>
<h1>Add a Subscriber</h1>

Next markup the content for the modal body

<div class="modal-body">
<label>Name</label><input type="text" ng-model=""/>
<label>Subscription Type</label><input type="text" ng-model="newUser.userType"/>
<label>Loyalty Score</label><input type="number" ng-model="newUser.loyalty"/>
<label>Date of Joining</label><input type="date"ng-model="newUser.joinDate"/>
<button class="btn btn-success" ng-click="saveNewUser()"> Save User</button>

Next add the code to your app/scripts/controllers/subscribers.js file as follows:

The Modal window makes use of the $modal service, so we will need to add it to our SubscribersCtrl as highlighted :

.controller('SubscribersCtrl', function ($scope, $modal) {

Next write the code to call the modal window.

Since the ‘Add New User’ will call the showModal function when clicked you will define that function at the end, just above the closing braces of your Subscribers Ctrl controller as follows:

$scope.showModel=function () {
var modalInstance = ${
templateUrl: 'views/add-user.html'})}

Another option that the $ method supports is the ‘controller’ which allows you to assign a controller that binds to the view within the modal. Now add the controller option to your modalInstance.

$scope.showModal=function () {
var modalInstance = ${
templateUrl: 'views/add-user.html',

Next create your AddNewUserCtrl within the same app/scripts/controllers/subscribers.js file.
Add this controller right at the end of the file after the SubscribersCtrl function ends.

.controller('AddNewUserCtrl', function ($scope, $modalInstance) {

Now within the AddNewUserCtrl define the functions for the cancel button as follows:

.controller('AddNewUserCtrl', function ($scope, $modalInstance) {
$scope.cancel =function(){

Save the files and check to see if the Add New User and the cancel buttons are working.