当我在angularjs中使用ui router重定向页面时,如何传递参数

How to pass parameter when I redirect the page in angularjs using ui router?

本文关键字:参数 何传递 重定向 router angularjs ui      更新时间:2023-09-26

我正在尝试通过ui-router状态传递参数。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..
})

我可以将页面重定向到second.html,但我似乎无法获得传递给我的secondCtrl的参数。有人能帮我一下吗?

谢谢。

首先你必须在route中添加参数。

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

现在添加第一个控制器

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

在第二个控制器注入$stateParams

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

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

$state.go("second", {'input' : $scope.userInput});

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

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

并在你的州注册:

  .state('second', {
        url: '/second/:input',
        templateUrl: 'second.html'
    })

除了在url中添加额外的参数外,还可以采用其他方式。

.state('second', {
    url: '/second',
    templateUrl: 'second.html',
    params: {input:null}
})

所有其他的变化将与其他答案相同。