Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown provider: $stateProviderProvider <- $stateProvider

.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.

like image 537
Alice Xu Avatar asked Jun 29 '15 15:06

Alice Xu


1 Answers

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) { ... })
like image 72
Dustin Avatar answered Nov 15 '22 03:11

Dustin