AngularJS Restful Routing

后端 未结 4 1386
滥情空心
滥情空心 2021-01-05 02:44

I\'m trying to structure my app using the Restful/Ruby convension //[method]/[id]. How I\'ve done it previously when using a server-side MVC fra

4条回答
  •  执笔经年
    2021-01-05 03:19

    This is now possible with ui-router 0.2.8:

    $stateProvider
        .state('base', {
            url: '/:resource/:collection/:id',
            controllerProvider: function( $stateParams )
            {   // assuming app.controller('FooCtrl',[…])
                return $stateParams.collection + 'Ctrl';
            },
            templateUrl: function( $stateParams )
            {
                return '/partials/' + $stateParams.collection + '.html';
            }
        });
    

    But in order to take advantage of $state.includes() on nav menus, this would probably be better:

    $stateProvider
        .state('base.RESOURCE_NAME1', {
            url: '/:collection/:id',
            controllerProvider: function( $stateParams )
            {   // assuming the convention FooCtrl
                return $stateParams.collection + 'Ctrl';
            },
            templateUrl: function( $stateParams )
            {
                return '/partials/' + $stateParams.collection + '.html';
            }
        }).state('base.RESOURCE_NAME2', {
            url: '/:collection/:id',
            controllerProvider: function( $stateParams )
            {   // assuming the convention FooCtrl
                return $stateParams.collection + 'Ctrl';
            },
            templateUrl: function( $stateParams )
            {
                return '/partials/' + $stateParams.collection + '.html';
            }
        });
    

    The above could be simplified with a loop to build the states from an array of resources ($stateProvider supports adding states basically whenever):

    var resources = [ 'r1', 'r2', '…' ];
    
    for ( var r = resources.length-1; r >=0; r-- )
    {
        var name = resources[r];
        $stateProvider.state('base.'+name, {
            …
        });
    }
    

    Caveat ui-router doesn't not really support optional state parameters (planned for v0.4)

提交回复
热议问题