You will need to save the modal instance and use it in the same controller. First you need to change your html like this:
<div ng-app="myApp">
<script type="text/ng-template" id="myModal.html">
<div class="modal-header">
<h3 class="modal-title">Modal title</h3>
</div>
<div class="modal-body">
Modal content
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="close(true)">OK</button>
<button class="btn btn-warning" ng-click="close(false)">Cancel</button>
</div>
</script>
<div ng-controller="MyCtrl">
<input type="button" value="Show modal" ng-click="showModal()"/>
</div>
And then in your controller:
.controller("MyCtrl", function($scope, $modal) {
var modalInstance = null;
$scope.close = function (ok, hide) {
if(ok) {
alert('ok');
} else {
alert('cancel');
}
modalInstance.dismiss();
};
var modalScope = $scope.$new();
$scope.showModal = function() {
modalInstance = $modal.open({
templateUrl: 'myModal.html',
scope: modalScope
});
}
});
When you want to control the modal in the same controller you need to have access to it, notice we are storing the result of the $modal
in a variable for later use.
That is equal to injecting modalInstance
to the other controller which lets you access close
, dismiss
or other functions on that object.