0

I know the same kind of question has been asked on SO many times, but I couldn't find the exact question that matches my requirement. So here's my question:

I have a function in my controller:

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');
            }
        );
};

I have 3 controllers having the same function. So I'm trying to refactor it in such a way that it is written in some service and can be called from all the controllers. What I've done so far is:

In Service:

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']; 

In Controller:

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

This code works without any error. But the question is, can passing $scope as an argument to a function is service cause any side effects? Is there any better alternate to this approach?

Thanks.

1 Answer 1

0

I would advise against passing $scope to the service. This makes your service dependent on the controller that is using it. What if another controller needed to use the service?

Instead, have the service return a promise, and in the controller do something like the following:

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

EDIT: Here's an example of how a modal dialog service could be implemented: http://weblogs.asp.net/dwahlin/building-an-angularjs-modal-service

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.