将当前参数设置为ui-sref

时间:2016-08-05 18:49:32

标签: javascript angularjs angular-ui-router

我尝试从导航中的ui-sref将当前项目id从网址发送到每个州:

index.html:

<body ng-controller="mainController as main" class="animated fadeIn">
    <!-- Working Group Header -->
    <div ng-include=" './partials/navigation.html' "></div>

    <!-- Routes -->
    <ui-view></ui-view>
</body>

navigation.html:

<ul >
    <li>
        <a title="About" ui-sref="about({id: id})">About</a>
    </li>
    <li>
        <a title="Files" ui-sref="files({id: id})">Files</a>
    </li>
    <li>
        <a title="Demos" ui-sref="demos({id: id})">Demos</a>
    </li>
</ul>

我的路由如下:

.config(function($stateProvider, $urlRouterProvider, $compileProvider) {
    //FOR UNMATCHED URL, REDIRECT TO HOME
    $urlRouterProvider.otherwise('about')

    // Set up routes
    $stateProvider
        .state('about', {
            url: '/wg/{id}/about',
            templateUrl: './partials/about.html',
            controller: 'aboutController'
        })
        .state('files', {
            url: '/wg/{id}/files',
            templateUrl: './partials/files.html',
            controller: 'filesController'
        })
        .state('demos', {
            url: '/wg/{id}/demos',
            templateUrl: './partials/demos.html',
            controller: 'demosController'
        })

   $compileProvider.debugInfoEnabled(false);
})

MainController:

    wg.controller('mainController', function($scope, $timeout, $stateParams){
    console.log('Entered home controller ')

    $scope.id = $stateParams.id;

})

我的网址:

  

的index.html#/ WG / 123 /约

然而,当我检查网址时,我会回来

  

的index.html#/ WG //约

1 个答案:

答案 0 :(得分:0)

$stateProvider定义中,您需要将param的语法从{id}更改为:id。然后,在注入id后,$stateParams.id应该可以使用$stateParams访问控制器。

$stateProvider
        .state('about', {
            url: '/wg/:id/about',
            templateUrl: './partials/about.html',
            controller: 'aboutController'
        })
        .state('files', {
            url: '/wg/:id/files',
            templateUrl: './partials/files.html',
            controller: 'filesController'
        })
        .state('demos', {
            url: '/wg/:id/demos',
            templateUrl: './partials/demos.html',
            controller: 'demosController'
        })

控制器示例:

.controller('demosController', ['$scope','$stateParams',function($scope, $stateParams) {
   $scope.id = $stateParams.id;  // <------ id now should be available in the child route controller
});