How inject $stateProvider in angular application?

2019-02-08 15:18发布

问题:

I try to use angular-ui, and try to inject $stateProvider:

html

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular-resource.min.js"></script>
    <script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
    <script src="test/appModule.js"></script>
</head>
<body>
    <div ng-app="appModule">
        <div ng-controller="appController">
            {{date}}
        </div>

    </div>
</body>
</html>

js (test/appModule.js)

var module = angular.module("appModule", ['ui.router']);

module.controller('appController', ['$scope', '$stateProvider',
    function ($scope, $stateProvider) {
        $scope.date = new Date();
    }]);

stack trace

Error: Unknown provider: $stateProviderProvider <- $stateProvider
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js:28:236
...

If I remove $stateProvider and ui.router with comments everything will work:

var module = angular.module("appModule"/*, ['ui.router']*/);
module.controller('appController', ['$scope'/*, '$stateProvider'*/,
    function ($scope, $stateProvider) {
        $scope.date = new Date();
    }]);

So the problem with injection $stateProvider any ideas about resolving?

P.S. I have tried ui sample it works, but I cannot figure out why mine does not.

回答1:

When using it in a controller you have to use $state:

angular.module("appModule", ['ui.router']).controller('appController', ['$scope', '$state', function ($scope, $state) {
    $scope.date = new Date();
}]);

You can only use the state provider in the config, for example:

angular.module('appModule').config(['$stateProvider', function($stateProvider){
    /* do w/e with state provider */
})];


回答2:

var bootstrapApp = angular.module('bootstrapDemoApp', ['ui.bootstrap','ui.router']);

bootstrapApp.config(function($stateProvider, $urlRouterProvider,$locationProvider) {




 // For any unmatched url, redirect to /
 $urlRouterProvider.otherwise("/");

 // Now set up the states
 $stateProvider
  .state('login', {
   url: "/",
   controller: "loginCtrl",
   templateUrl: "partials/login.html"
 })
});