0

Service:

app.service('myService', ['$scope', '$timeout', function($scope, $timeout){
   return {
      fn: function(messageTitle, messageContent) {
        $timeout(function() {
            $scope.fadeMessageSuccess = true;
        }, 3000);
      }
   }
}]);

Controller:

app.controller("AccountCtrl", ["$scope", "Auth", "$timeout", "myService",
  function($scope, Auth, $timeout, myService) {
    myService.fn();
    $scope.createUser = function() {
      $scope.message = null;
      $scope.error = null;

      // Create a new user
      Auth.$createUserWithEmailAndPassword($scope.accountEmailAddress, $scope.accountPassword)
        .then(function(firebaseUser) {
          $scope.message = "User created with uid: " + firebaseUser.uid;
          console.log($scope.message);
        }).catch(function(error) {
          $scope.error = error;
          console.log($scope.error);
        });
    };
  }
]);

I'm trying to create a service so that I can use a function in multiple controllers but I'm have trouble getting this first one working. This is the error message I'm getting in console:

angular.js:13550Error: [$injector:unpr]
Joe Berthelot
  • 675
  • 4
  • 13
  • 29
  • Using the non-minified angularjs file should give you a more detailed error message. – Jukebox Jan 05 '17 at 23:37
  • See [this post](http://stackoverflow.com/questions/22898927/injecting-scope-into-an-angular-service-function). Injecting `$scope` into a service doesn't make sense. – kevin Jan 05 '17 at 23:41

2 Answers2

0

Just an observation: doesn't look like you're passing anything to the function when you're calling it. And not sure if you're wanting to add any more functionality to the service, but I think you can return the function directly and just call "myService(title, content);". But I don't think those issues would cause what you're encountering.

0

It looks like you were trying to return an object (a la the .factory() function) when you were trying to use .service(). Here is a dead simple explanation for .factory, .service, and .provider.

As pointed out by user2341963, injecting $scope into a service doesn't make much sense.

Also, are you sure all of your dependencies are defined and available to Angular?

Here is an example Plunkr of using a service in a controller.

Community
  • 1
  • 1
Jukebox
  • 1,593
  • 1
  • 16
  • 27