我正在尝试使用angular&#; $ routeProvider和$ routeParams来控制我的应用程序中的路由。在所有路线中,我定义了以下路线 -
$routeProvider
.when("/home",{
templateUrl : "home.html",
controller : "HomeController"
})
.when("studentDetails/:student",{
templateUrl : "studentDetails.html",
controller : "StudentController"
})
.otherwise({redirectTo:"/home"});
});
在我的家庭控制器中,我有一个功能,可以在点击事件中导航到学生控制器,如下所示 -
$location.path("/studentDetails/" + studentDetails); // student details is a json.
我在StudentController中访问此变量,如下所示 -
(function(){
var StudentController = function($scope, $routeParams){
$scope.details = $routeParams.student;
};
var app = angular.module("dummy");
app.controller("StudentController",StudentController);
}());
我面临的问题是,如果我传递一个简单的变量(一个字符串作为studentDetails),代码就可以工作,但是json失败了。这是预期的行为还是我做错了什么? 如果无法使用$ routeParams传递json,那么理想的做法应该是什么?
答案 0 :(得分:1)
理想的方法是将studentDetails字符串化。就这样做。 在点击事件的学生控制器中,
var str = JSON.stringify(studentDetails);
$location.path("/studentDetails/" + str );
并在StudentController中
$scope.details = JSON.parse($routeParams.student);
多数民众赞成!!
答案 1 :(得分:0)
尝试以下
而不是传递json变量传递为多变量
$location.path("/studentDetails/" + studentId+'/'+studentName);
和路线
.when("studentDetails/:studentId/:studentName",{
templateUrl : "studentDetails.html",
controller : "StudentController"
})
答案 2 :(得分:0)
要使用$location.path
传递对象,请使用$httpParamSerializer
服务。
$location.path("/studentDetails/" + studentId +
'?' + $httpParamSerializer(studentDetails)
);
$httpParamSerializer
服务将对象转换为URL search query string。
路线参数是$location
的{{1}}和search()
的组合。当path()
路径匹配时,将提取路径参数。
如果参数名称冲突,$route
参数优先于path
参数。 1
答案 3 :(得分:0)
// var str = JSON.stringify(studentDetails);
// $location.path("/studentDetails/" + str );
// $scope.details = JSON.parse($routeParams.student);
呃,不正确!
//.when('/hs/:id/:name', {
//$location.path("/hs/1/thuc101")