Calling another controller within AngularJS UI Boo

2019-07-23 14:53发布

问题:

I have a completely working version of the ui.bootstrap.modal as per the example here http://angular-ui.github.io/bootstrap/#/modal but I want to take a stage further and add it to my controller configuration.

Perhaps I'm taking it too far (or doing it wrong) but I'm not a fan of just

var ModalInstanceCtrl = function ($scope...

My modal open controller:

var controllers = angular.module('myapp.controllers', []);


controllers.controller('ModalDemoCtrl', ['$scope', '$modal', '$log',
    function($scope,  $modal, $log) {

        $scope.client = {};

        $scope.open = function(size) {
            var modalInstance = $modal.open({
                templateUrl: 'templates/modals/create.html',
                controller: ModalInstanceCtrl,
                backdrop: 'static',
                size: size,
                resolve: {
                    client: function () {
                        return $scope.client;
                    }
                }
            });

            modalInstance.result.then(function (selectedItem) {
                $log.info('Save changes at: ' + new Date());
            }, function () {
                $log.info('Closed at: ' + new Date());
            });
        };
    }
]);

Modal instance controller:

var ModalInstanceCtrl = function ($scope, $modalInstance, client) {

    $scope.client = client;

    $scope.save = function () {
        $modalInstance.close(client);
    };

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

However I would like to change this last controller to:

controllers.controller('ModalInstanceCtrl', ['$scope', '$modalInstance', 'client',
    function ($scope, $modalInstance, client) {

        $scope.client = client;


        $scope.save = function () {
            $modalInstance.close(client);
        };

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

If I also update the controller reference within $scope.open for ModalDemoCtrl controller to

controller: controllers.ModalInstanceCtrl

then there are no errors but the save and cancel buttons within the modal window no longer work.

Could someone point out where I am going wrong - possibly a fundamental lack of understanding of the way controllers work within the AngularJS?!

回答1:

Controller specified in $scope.open needed single quotes around it.

 controller: 'ModalInstanceCtrl',


回答2:

You are referencing your module to variable controllers.

All controllers in angular systems has unique names.

The controller is still "ModalInstanceCtrl" not "controllers.ModalInstanceCtrl".