小编典典

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

angularjs

我正在尝试通过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..
})

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

谢谢。


阅读 333

收藏
2020-07-04

共1个答案

小编典典

首先,您必须在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;
})
2020-07-04