简体   繁体   中英

cannot use a different controller with a view with ui-router AngularJS

I'm using ui-router for routing my angular app. I have the following route:

'use strict';

//Setting up route
angular.module('admins').config(['$stateProvider', 
    function($stateProvider) {
        // Admins state routing
        $stateProvider.
        state('admin_home', {
            url: '/admin',
            templateUrl: 'modules/admins/views/list-admins.client.view.html'
        }).
        state('adduser', {
            url: '/admin/create',
            templateUrl: 'modules/admins/views/create-admin.client.view.html', 
        }).
        state('viewAdmin', {
            url: '/admins/:adminId',
            templateUrl: 'modules/admins/views/view-admin.client.view.html'
        }).
        state('editAdmin', {
            url: '/admins/:adminId/edit',
            templateUrl: 'modules/admins/views/edit-admin.client.view.html'
        });
    }
]);

This is within my 'Admin' module, and that has its own controller (AdminsController).

However, I want to be able to create a new user from here, and the controller to do that is called 'AuthenticationController' and is elsewhere in the structure.

As far as I know, I should be able to put something like:

state('adduser', {
                url: '/admin/create',
                templateUrl: 'modules/admins/views/create-admin.client.view.html',
                controller:'AuthenticationController'

            })

and it should work.

However - I keep getting redirected back to the index page.

I suspect this may be because I'm using HTML5 and have this in my config also:

// use HTML 5
         $locationProvider.html5Mode(true).hashPrefix('!');
            //Sets the HTTP header type for the redirects
           $httpProvider.defaults.headers.common = {
            'Accept': 'application/json', 
            'Content-Type': 'application/json'

Can anyone help?

You should add :

$urlRouterProvider.otherwise("/home");

And declare your controller inside your state function (not in your view files) like that :

 state('viewAdmin', {
        url: '/admins/:adminId',
        controller : AdminsController,
        templateUrl: 'modules/admins/views/view-admin.client.view.html'
 })

If it doesn't work, try to remove :

 $locationProvider.html5Mode(true).hashPrefix('!');
            //Sets the HTTP header type for the redirects
 $httpProvider.defaults.headers.common = {
     'Accept': 'application/json', 
     'Content-Type': 'application/json'

Let me know ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM