0

I made this code based on a tutorial. I want to know how I can use a single controller. I want to generate this dialog box, using only a controller.

http://fiddle.jshell.net/adnu6mmt/2/?utm_source=website&utm_medium=embed&utm_campaign=adnu6mmt

In this project I currently use 2 controllers. Thank you.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.