在服务angularjs中的函数中使用$scope

Using $scope in a function in service angularjs

本文关键字:scope 服务 angularjs 函数      更新时间:2023-09-26

我知道同样的问题已经被问了很多次,但我找不到符合我要求的确切问题。所以我的问题是:

我的控制器中有一个功能:

showPNG = function() {
        var pngPromise = $modal({
            template: 'index.html',
            persist: true,
            show: false,
            backdrop: 'static',
            scope: $scope,
            modalClass: 'preview-png'
        });
        $q.when(pngPromise).then(
            function(pngElement) {
                pngElement.modal('show');
            }
        );
};

我有三个具有相同功能的控制器。因此,我试图以这样一种方式对它进行重构,即它是在某个服务中编写的,并且可以从所有控制器中调用。到目前为止,我所做的是:

服务中:

var service = module.exports =   function ($modal, $q) {
        return {
            showPNG : function(scope) {
                var pngPromise = $modal({
                    template: 'index.html',
                    persist: true,
                    show: false,
                    backdrop: 'static',
                    scope: scope,
                    modalClass: 'preview-png'
                });
                $q.when(pngPromise).then(
                    function(pngElement) {
                        pngElement.modal('show');
                    }
                );
            }
        };
};
service.$inject = ['$modal', '$q']; 

在控制器中:

...
    myService.showPNG($scope);
...

此代码工作时没有任何错误。但问题是,将$scope作为参数传递给函数是否为服务会产生任何副作用?有没有更好的替代方法?

谢谢。

我建议不要将$scope传递给服务。这使您的服务依赖于使用它的控制器。如果需要另一个控制器使用该服务怎么办?

相反,让服务返回一个承诺,并在控制器中执行以下操作:

.controller("ctrl1", ["$scope", "service", function($scope, service){
   $scope.showModal = false;
   service.showPNG()
      .then(function(shouldShow){
         $scope.showModal = shouldShow;
         $scope.$apply(); // assuming showPNG is async
      });
}]);

编辑:下面是一个如何实现模式对话框服务的示例:http://weblogs.asp.net/dwahlin/building-an-angularjs-modal-service