0

how can i get the $scope variables in app.factory ????

app.factory('ws', function ($http) {
     console.log($scope.variable);
})

I am getting error $scope is not defined

georgeawg
  • 46,994
  • 13
  • 63
  • 85
  • https://stackoverflow.com/questions/22898927/injecting-scope-into-an-angular-service-function – Urielzen Mar 31 '19 at 15:45
  • Be careful, the accepted answer to the duplicate uses some bad practices. Namely it doesn't return a promise, consequently the controller does not know when data has arrived from the server. – georgeawg Mar 31 '19 at 22:49

1 Answers1

0

"Services are singletons, and it is not logical for a scope to be injected in service (which is case indeed, you cannot inject scope in service). You can pass scope as a parameter, but that is also a bad design choice, because you would have scope being edited in multiple places, making it hard for debugging. Code for dealing with scope variables should go in controller, and service calls go to the service."

Injecting $scope into an angular service function()

Urielzen
  • 409
  • 5
  • 15
  • I use $ rootscope instead of $ scope ?? – user3609955 Mar 31 '19 at 15:58
  • You should not use dependency injection to inject neither $scope nor $rootscope to your factory. Instead, your factory should have some methods, and those methods, if they need $scope, you should pass $scope as a parameter only to those methods that need it. – Urielzen Mar 31 '19 at 20:23