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

ε祈祈猫儿з 提交于 2019-12-18 12:56:43

问题


I am trying to pass parameters via the ui-router state.go

However, I am not sure how to pass the parameters. Here are my codes

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..
})

I can redirect the page to second.html but I can't seem to get the parameter that is passed to my secondCtrl. Can anyone help me about it?

Thanks.


回答1:


First you have to add parameter in route.

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

Now add in first controller

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

}]);

In second controller inject $stateParams

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



回答2:


You could do this way in the first controller:-

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

In the second controller inject $stateParams service.

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

and register that in your state:

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



回答3:


Instead of adding additional param in the url, you could do it on the other way.

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

})

All other changes would be same with what other answers.



来源:https://stackoverflow.com/questions/25298533/how-to-pass-parameter-when-i-redirect-the-page-in-angularjs-using-ui-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!