-1

I have a very basic factory and controller in AngularJS, took it from another post on Stack Overflow

var app = angular.module( 'testapp', [] );
app.factory('commonService', function ($scope) {
  var obj= {};
  obj.func = function () {
    console.log('route 1');
  }
  obj.func1 = function () {
    console.log('route 2');
  }
  return obj;
});
app.controller('FirstController', function ($scope, commonService) { 
  console.log('route 1' + commonService.func());  
});
app.controller('SecondController', function ($scope, commonService) { 
  console.log('route 2' + commonService.func1());  
});

For some reason this keep giving me the error Unknown provider: $scopeProvider <- $scope <- commonService

I am trying to use a factory in order to clean up my code and re-use some functions in my controller; I have tried using a service and had the same results.

ndrb
  • 53
  • 1
  • 7
  • where the "FirstController" is called? – aseferov Apr 25 '16 at 16:53
  • I have a very basic HTML file
    – ndrb Apr 25 '16 at 16:55
  • @nrdb [Here](https://jsfiddle.net/z4xu0trf/) is a working JSFiddle. – Igor Raush Apr 25 '16 at 16:56
  • Ok, after fixing a typo with the controller name, i am getting a different error: Unknown provider: $scopeProvider – ndrb Apr 25 '16 at 16:57
  • @IgorRaush thanks for that fiddle, i am no longer getting errors, i can see the console.log() but it thinks the two functions in the factory are undefined – ndrb Apr 25 '16 at 17:06
  • @nrdb If you are referring to the `route 1undefined` you see in the logs, it's just because you are appending the result of `commonService.func()` to your log message. `commonService.func` does not have a return, so calling it gives `undefined`. – Igor Raush Apr 25 '16 at 17:38
  • @IgorRaush oh my bad! did not see that! thanks again for the help, kinda new to angular and still learning the flow of it all. Much appreciated!! – ndrb Apr 25 '16 at 17:42
  • @nrdb, no problem! Note that the primary issue with your code (other than the typo) is your injection of `$scope` into a factory, which is fundamentally incorrect (`$scope` is only injectable into controllers). Please take a look at the [link](https://stackoverflow.com/questions/22898927/injecting-scope-into-an-angular-service-function) in the answer below for a great explanation. Also, edit your question with the new error message you got after fixing the typo; that issue is more interesting. – Igor Raush Apr 25 '16 at 17:59

1 Answers1

1

The problem is you are injecting $scope into the factory but it cannot access your $scope. Also it doesn't make much sense to pass $scope into your factory. Take look at this.

sebenalern
  • 2,393
  • 3
  • 20
  • 34