Angular Modal Window Example using $modal.open 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:

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

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>
<h3>Add a Subscriber</h3>
</div>

Next markup the content for the modal body

<div class="modal-body">
<label>Name</label><input type="text" ng-model="newUser.name"/>
<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"/>
<br/>
<button class="btn btn-success" ng-click="saveNewUser()"> Save User</button>
</div>

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 :

angular.module('hlApp')
.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 () {
$scope.newUser={};
var modalInstance = $modal.open({
templateUrl: 'views/add-user.html'})}

Another option that the $modal.open 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 () {
$scope.newUser={};
var modalInstance = $modal.open({
templateUrl: 'views/add-user.html',
controller:'AddNewUserCtrl'
})}

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(){
$modalInstance.dismiss('cancel');
}
});

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