Calling another controller within AngularJS UI Bootstrap Modal

大城市里の小女人 提交于 2019-12-11 03:40:39

问题


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".



来源:https://stackoverflow.com/questions/24151704/calling-another-controller-within-angularjs-ui-bootstrap-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!