1
votes

I'm very new to Angular and I'm trying to get an AngularJS modal to work. It displays fine when I click the button but the cancel button inside the modal does not work.

myApp.controller("ServiceController", function($scope, $http, $modal) {
    var modalInstance;
    $scope.select = function(id) {
        this.modalInstance = $modal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'myModalContent.html',
            controller: 'ServiceController',
        });

        console.log(this.modalInstance);
    };

    $scope.cancel = function() {
        console.log(this.modalInstance); <--- this is null
        this.modalInstance.dismiss('cancel');
    };
});

The error occurs in the Cancel function as the modalInstance variable is null.

Can anyone please explain why this is null, even though the select method clearly assigns a modal instance to it.

This is what the HTML code looks like:

<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-header">
        <h3 class="modal-title">update this line</h3>
    </div>
    <div class="modal-body">
        <input class="form-control" ng-model="client.name"/>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary">Update</button>
        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
    </div>
</script>

Thanks

1
what is the value of this when the error is thrown?Will Reese
@WillReesethis contains a modalInstance: Objectdonga

1 Answers

0
votes

The approach recommended on the angular boostrap site is to use a separate controller for your Modal. This helps modularize your code as well as keep the different functionalities separate. Try this:

myApp.controller("ServiceController", function($scope, $http, $modal) {
    $scope.select = function(id) {
        var modalInstance = $modal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'myModalContent.html',
            controller: 'modalController',
        });

        console.log(modalInstance);
    };
});

myApp.controller('modalController', function ($scope, $modalInstance, items) {

  $scope.cancel = function () {
    console.log(modalInstance);
    $modalInstance.dismiss('cancel');
  };
});