Pindakaas
Pindakaas

Reputation: 4439

how to use stateprovider in angular?

Trying to use a state router in angular:

var app =angular.module('myapp', ['ui.bootstrap','ui.router']);

app.controller('TabsDemoCtrl', function ($scope, $window) {

    $scope.tabs = [
        { title:'Orders', content:'Dynamic content 1' },
        { title:'Awaiting settlement', content:'Dynamic content 2' },
        { title:'Complete', content:'Dynamic content 3' }
    ];

});

app.config(function($stateProvider,$state) {
    // Now set up the states
    $stateProvider
        .state('orders', {
            templateUrl: '../partials/orders.html',
            controller: 'ordersCtrl'

        });

    $state.go('orders');
});

I am getting this error:

Uncaught Error: [$injector:modulerr] Failed to instantiate module WIP due to:
Error: [$injector:unpr] Unknown provider: $state

Upvotes: 2

Views: 1330

Answers (2)

Sudharsan S
Sudharsan S

Reputation: 15403

Use .run in app module

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

app.run(function($state) { 
    $state.go('orders');
});

app.config(function($stateProvider) {
  // Now set up the states
  $stateProvider
    .state('orders', {
       url : '/orders',
       templateUrl: '../partials/orders.html',
        controller: 'ordersCtrl'
   });
});

SEE MORE In SO

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

provider are only accessible in config phase with Provider post-fix Like you want to access $state provider then it would be $stateProvider

You can not access $state in config phase, $state is provider

Removing $state from function will fix your issue.

For re redirecting to default state I'd prefer you to use $urlRouterProvider & mention your URL in that, that will redirect to /orders when url doesn't match any state which makes more sense.

Config

app.config(function($stateProvider, $urlRouterProvider) {
    // Now set up the states
    $stateProvider
        .state('orders', {
            url: '/order',//just for demonstration
            templateUrl: '../partials/orders.html',
            controller: 'ordersCtrl'
        });
    $urlRouterProvider.otherwise('/orders');
});

Upvotes: 1

Related Questions