5
.controller('myCtrl', function($scope,$localstorage,$stateProvider, $urlRouterProvider) {

  $scope.getNews= function(){
  $stateProvider.stat('app.news')
}

});

Why I am getting error of unknown provider? I already injected the dependecy to my controller.

Alice Xu
  • 533
  • 6
  • 20
  • 4
    i think its `$state` not `$stateProvider` and note that you have missed a comma `,` between `$scope` and `$localstorage`. `$stateProvider` is something you need to inject in to the `app.config` block – Kalhan.Toress Jun 29 '15 at 15:41
  • @Alice Xu if so please accept/vote it. – ooozguuur Dec 16 '15 at 07:54

1 Answers1

12

You issue is that you're trying to add the $stateProvider to a controller, rather than to your app.config() function. If you review the UI-Router docs, you'll see that you should configure it in app.config, which will load before your controller is launched.

You can read data from the $state provider in your controller, but only when you use it as a service. It can be a confusing difference. I try to explain below.

In Angular, you can create three types of services: providers, factories, and services. There are several differences, which aren't particularly critical for this answer, but you can read about the differences here: AngularJS: Service vs provider vs factory

In this case, it's important to know that a Provider is the only type of service that can be injected into the app's config() function. Often times, functionality of a Provider is also useful in your controller. For example, you may configure $stateProvider routes in to you config(), but you may want to read the name of the current state in you controller.

Now, here's where it gets tricky: $stateProvider is a provider, and Angular requires you to call it $stateProvider when you inject it into your config(). However, it can also be used as a service, but when you inject a service into a controller, you cannot specify the service type. So, $stateProvider becomes $state. This has to do with how the $get method is assigned, which you can read all about here: https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection

So, if you are trying to configure your routes, include them in your config:

myApp.config(function($stateProvider, $urlRouterProvider) { ... })

If you are trying to read information about the current state, you can inject it into your controller:

myApp.controller('myCtrl', function($state) { ... })
Community
  • 1
  • 1
Dustin
  • 846
  • 8
  • 13
  • 2
    what if I want to use a service for the configuration of my routes? I would need to register my routes that in the .run()? Would that work? – chesscov77 Nov 16 '15 at 19:42
  • This also applies to unit testing routes. I was injecting the provider but was getting errors until I replaced it with just plain `$state`. – Todd Mar 11 '19 at 21:52