角度路由与请求参数失败

时间:2014-07-10 13:58:42

标签: angularjs angularjs-directive angularjs-scope

我正在尝试使用ng-view以角度路由到表单提交上的部分模板。除了网址,我传递的参数?username=Joe,我希望使用$routeParams在新的部分中检索。

如果我没有传递任何参数,路由就可以工作:$location.path('/submit'); 但是,如果我传递参数:$location.path('/submit?userName=joe');

,则表单按钮不起作用

角度代码:

的index.html:

<body>
<div ng-view></div>
</body>

loginPartial.html:

<form ng-submit="submit()">
    <button type="submit">Submit</button>
</form>

messagePartial.html:

<p>Hello {{userName}}<p>

角度代码:

angular.module('app',['ngRoute'])
.config(['$routeProvider',
function($routeProvider){
    $routeProvider
        .when('/',{
            templateUrl:'loginPartial.html',
            controller:'LoginController'
        })
        .when('/submit',{
            templateUrl:'messagePartial.html',
            controller:'MessageController'
        })
        .otherwise({
            redirectTo:'/'
        });

}])
.controller('LoginController',['$scope','$location',
function($scope,$location){
    $scope.submit=function(){
    $location.path('/submit');//routing works with no parameters passed
    //$location.path('/submit?userName=joe');//routing fails if parameters passed
    };
}])
.controller('MessageController',['$scope','$routeParams',
function($scope,$routeParams){
    $scope.userName=$routeParams.userName;
}]);

1 个答案:

答案 0 :(得分:0)

您需要使用$location.path('/submit').search({userName:'Joe'})

此外,如果您发现$routeParams无效,请尝试注入$route,然后在您的控制器中使用:var _params = $route.current.params