使用ui路由器在angularjs中重定向页面时如何传递参数?

Fly*_*Cat 14 javascript angularjs angular-ui

我试图通过ui-router state.go传递参数

但是,我不知道如何传递参数.这是我的代码

app.config(function($stateProvider) {    
    $stateProvider
        .state('first', {
            url: '/first',
            templateUrl: 'first.html'
        })
        .state('second', {
            url: '/second',
            templateUrl: 'second.html'
        })
})

//my first.html
app.controller.('firstCtrl' ,["$scope", "$state", function($scope, $state){
    $scope.userInput <- come from user
    $scope.clickThis=function() {
        $state.go("second", $scope.userInput);
    }

}]);

//my second.html
app.controller.('secondCtrl,["$scope", "$state", function($scope, $state){
    //How do I get the parameter that is passed to here..
})
Run Code Online (Sandbox Code Playgroud)

我可以将页面重定向到second.html,但我似乎无法获取传递给我的secondCtrl的参数.任何人都可以帮我吗?

谢谢.

Dar*_*n P 28

首先,您必须在路线中添加参数.

app.config(function($stateProvider) {    
    $stateProvider
        .state('first', {
            url: '/first',
            templateUrl: 'first.html'
        })
        .state('second', {
            url: '/second/:id',
            templateUrl: 'second.html'
        })
});
Run Code Online (Sandbox Code Playgroud)

现在添加第一个控制器

app.controller.('firstCtrl' ,["$scope", "$state", function($scope, $state){
    $scope.userInput <- come from user
    $scope.clickThis=function() {
        $state.go("second", { id: $scope.userInput });
    }

}]);
Run Code Online (Sandbox Code Playgroud)

在第二个控制器注入$ stateParams

//my second.html
app.controller.('secondCtrl',["$scope", "$state", "$stateParams", function($scope, $state, $stateParams){
    $scope.id = $stateParams.id;
})
Run Code Online (Sandbox Code Playgroud)

  • 如何使用上述方式传递对象?在上面的例子中,它显示了 URL 中“id”的值,显然如果我想传递一个对象,我也不想在 URL 中显示它。那怎么可能呢? (2认同)

PSL*_*PSL 5

你可以在第一个控制器中这样做: -

$state.go("second", {'input' : $scope.userInput});
Run Code Online (Sandbox Code Playgroud)

在第二个控制器中注入$ stateParams服务.

app.controller('secondCtrl',["$scope", "$stateParams", function($scope, $stateParams){
    var data = $stateParams.input;
}]);
Run Code Online (Sandbox Code Playgroud)

并在您的州注册:

  .state('second', {
        url: '/second/:input',
        templateUrl: 'second.html'
    })
Run Code Online (Sandbox Code Playgroud)