如何在主app控制器中加载/注入服务?

时间:2017-02-03 11:23:56

标签: javascript angularjs

我正在尝试从this answer实现模式,但我无法在app控制器中使用该服务。问题很简单:如何在modalService主控制器中使用emaApp注入?

modal.js

angular.module('emaApp', []).service('modalService', [ '$modal',
// NB: For Angular-bootstrap 0.14.0 or later, use $uibModal above instead of $modal
function($modal) {

    var modalDefaults = {
        backdrop : true,
        keyboard : true,
        modalFade : true,
        templateUrl : '/app/partials/modal.html'
    };

    var modalOptions = {
        closeButtonText : 'Close',
        actionButtonText : 'OK',
        headerText : 'Proceed?',
        bodyText : 'Perform this action?'
    };

    this.showModal = function(customModalDefaults, customModalOptions) {
        if (!customModalDefaults)
            customModalDefaults = {};
        customModalDefaults.backdrop = 'static';
        return this.show(customModalDefaults, customModalOptions);
    };

    this.show = function(customModalDefaults, customModalOptions) {

        //Create temp objects to work with since we're in a singleton service
        var tempModalDefaults = {};
        var tempModalOptions = {};

        //Map angular-ui modal custom defaults to modal defaults defined in service
        angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);

        //Map modal.html $scope custom properties to defaults defined in service
        angular.extend(tempModalOptions, modalOptions, customModalOptions);

        if (!tempModalDefaults.controller) {
            tempModalDefaults.controller = function($scope, $modalInstance) {
                $scope.modalOptions = tempModalOptions;
                $scope.modalOptions.ok = function(result) {
                    $modalInstance.close(result);
                };
                $scope.modalOptions.close = function(result) {
                    $modalInstance.dismiss('cancel');
                };
            };
        }

        return $modal.open(tempModalDefaults).result;
    };

} ]);

index.js

var app = angular.module('emaApp', []);

app.controller('mainCtrl',['$scope', '$http', 'modalService', function($scope, $http, modalService) {

    $scope.deleteModel = function(modelId) {

        var modalOptions = {
            closeButtonText : 'Cancel',
            actionButtonText : 'Delete Customer',
            headerText : 'Delete ' + modelId + '?',
            bodyText : 'Are you sure you want to delete this model?'
        };

        modalModule.showModal({}, modalOptions).then(function(result) {
            //your-custom-logic
            alert("muaha")
        });
    }

}]);

2 个答案:

答案 0 :(得分:1)

您多次定义模块emaApp。因此,覆盖现有模块,您需要检索稍后加载的文件中的模块,即 index.js ,通知已删除 []

var app = angular.module('emaApp');

而不是

var app = angular.module('emaApp', []);

答案 1 :(得分:0)

您已将服务注入控制器。您应该在控制器中使用modalService而不是-possibly- undefined modalModule