KingFish
KingFish

Reputation: 9153

ui-router: Integrating with existing controllers

I am in the process of converting my current angular project to use ui-router and I am a little confused. The documentation states I add my controller as such:

$stateProvider.state('contacts.detail', {
   url: '/contacts/:contactId',   
   controller: function($stateParams){
      $stateParams.contactId  //*** Exists! ***//
   }
})

I have defined my old controller in this manner:

xap.controller('DemoCtrl', [$scope, function ($scope, demoService) {
})

where xap is defined as:

var xap = angular.module({ .... })

What is the correct integration method?

Thanks

Upvotes: 1

Views: 346

Answers (2)

slim
slim

Reputation: 469

The controller in the state is not a resolve field. In the state, you have to put only controller name because when you declare it, it's "injected" into your angular module.

So, you have to put controller name like this :

$stateProvider.state('contacts.detail', {
   url: '/contacts/:contactId',   
   controller: 'ContactsCtrl'
});

If you want to inject some variable, you can add an object in the state like this :

$stateProvider.state('contacts.detail', {
   url: '/contacts/:contactId',   
   controller: 'ContactsCtrl',
   myVar: function(...){
       return '...';
   }
});

So, if you put a function, it's for a resolve field and not for controllers... You can implement it into state but it's better to do it outside state declaration.

Upvotes: 0

Ateş Göral
Ateş Göral

Reputation: 140050

You can refer to a pre-registered controller by name:

$stateProvider.state('contacts.detail', {
    url: '/contacts/:contactId',   
    controller: 'DemoCtrl'
});

You can add the $stateParams dependency to your controller to access parameters:

xap.controller('DemoCtrl', [
    '$scope',
    '$stateParams',
    'demoService',
    function ($scope, $stateParams, demoService) {
        $stateParams.contactId //*** Exists! ***//
    }
]);

But you can also inline your controllers and therefore not have to come up with unique names for each controller for every state:

$stateProvider.state('contacts.detail', {
    url: '/contacts/:contactId',   
    controller: [
        '$scope',
        '$stateParams',
        'demoService',
        function ($scope, $stateParams, demoService) {
            $stateParams.contactId //*** Exists! ***//
        }
    ]
});

Upvotes: 3

Related Questions