R Claven
R Claven

Reputation: 1210

Is it improper, and if so why, to pass $scope to a service in Angularjs?

Are there strong reasons one should not pass $scope to a service?

I realize services are to be reusable singletons and so passing a (potentially) large object to the service might have maintenance issues, but let's assume solid documentation that would declare "the following members of $scope are required." I just think it looks cleaner than passing in 4-6 parameters.

Any other concerns for this practice would be greatly appreciated. I am being evaluated on this piece of code! :)

Incidentally, I JUST realized how active the angularJS community is on here and I am very grateful!!

Upvotes: 2

Views: 107

Answers (1)

adib.mosharrof
adib.mosharrof

Reputation: 1634

Read this article 5 Guidelines For Avoiding Scope Soup in Angular

In point 5, he explains the reason for not passing $scope to Services.

I will quote some of his writing here

The problem with relying on values to be set from a parent controller, or relying on a child controller to set data back up on the parent scope, is that you end up with an implicit coupling that isn't easy to see at first.

Worse, it means the controller implementation is completely dependent on the ordering of the bindings in the view! I can't use or test those controllers independently of each other, because they are coupled together by $scope.

$scope should be used as a glue between View andController. If you want to send some value from $scope to a service, just extract those values out and pass them to the service.

If you see that you are having to pass too many values, consider grouping the values in objects and then passing them.

Changing few things in $scope, might affect your app in unwanted ways.

It is an anti-pattern to use $scope outside controllers.

Upvotes: 6

Related Questions