【问题标题】:How to pass parameter when I redirect the page in angularjs using ui router?当我使用ui路由器在angularjs中重定向页面时如何传递参数?
【发布时间】:2014-08-14 01:02:42
【问题描述】:

我正在尝试通过 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 的参数。 谁能帮帮我?

谢谢。

【问题讨论】:

    标签: javascript angularjs angular-ui


    【解决方案1】:

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

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

    【讨论】:

    • 如何使用上述方式传递对象?在上面的例子中,它在 URL 中显示“id”的值,显然如果我想传递一个对象,我也不想在 URL 中显示它。那怎么可能呢?
    • 谢谢你救了我的命!
    • awesome dude.. 顺便说一句,一个常见的错误是,人们不会将变量名称与模板 url 中的相同...
    【解决方案2】:

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

    $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'
        })
    

    【讨论】:

    • 感谢您的帮助。我给 Daus908 绿色,因为他表示我需要在路由中添加参数,这是我所缺少的。:D +1
    • @FlyingCat np。我想我在这个答案中也提到了它。然而,另一个答案是在我之前 6 秒出现的.. :)
    【解决方案3】:

    您可以通过其他方式来代替在 url 中添加额外的参数。

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

    所有其他更改将与其他答案相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多