[英]AngularJS not routing properly
我正在学习Angular,所以这是我的testapp: http : //enrolin.in/test/#/students
现在在这里,我想按名称搜索数据库。 所以我创建了php,它返回的正是我所需要的。 这是php: http : //enrolin.in/test/login.php ?p= fetchbyname&& name= ak您必须将url中的名称替换为需要搜索的任何内容。 我还创建了一个部分页面,该页面返回绝对正确的结果,这是该页面: http : //enrolin.in/test/#/studentSearch/ak到目前为止,一切都很好,但这是问题所在:
当我尝试在http://enrolin.in/test/#/students中搜索时,angularJS不会将我路由到类似http://enrolin.in/test/#/studentSearch/ak的位置 ,而是将其路由到默认值已在$ routeProvider中设置
这是我的angularJS(我删除了一些不重要的代码):
路线提供者:
.config(function ($routeProvider) {
$routeProvider
.when("/students/:id", {
templateUrl: "templates/studentDetails.html",
controller: "studentDetailsController"
})
.when("/studentSearch/:name", {
templateUrl: "templates/studentSearch.html",
controller: "studentSearchController"
})
.otherwise({
redirectTo: "/home"
})
})
传递链接的控制器:
.controller("studentsController", function ($scope, $http, $route,$location) {
$scope.searchStudent=function(){
if($scope.name){
$location.url("/studentsSearch/" + $scope.name);
}
else{
$location.url("/studentsSearch/");
}
}
$scope.reloadData=function(){
$route.reload();
}
$http.get("http://enrolin.in/test/login.php?p=fetchall")
.then(function (response) {
$scope.students = response.data;
})
})
提取数据并显示的控制器:
.controller("studentSearchController", function ($scope, $http, $routeParams) {
if($routeParams.name)
{
$http({
url: "http://enrolin.in/test/login.php?p=fetchbyname&&name=",
method: "get",
params: { name: $routeParams.name }
}).then(function (response) {
$scope.studs = response.data;
})
}
else
{
$http.get("http://enrolin.in/test/login.php?p=fetchall")
.then(function (response) {
$scope.students = response.data;
})
}
})
以前,每次我想在html中放置一个链接时,都会使用以前写过的<a href="#/courses">courses</a>
这样的路由,但是现在当我想将其放置在函数中时,我不确定来写。 请帮忙。
嗨@AkhilEshKhajuria,
您使用的名称与路由配置中提到的名称不同。 路由名称是“ / studentSearch /:name?” 但是您已在函数中使用“ / studentsSearch /”。
请尝试替换$location.url("/studentsSearch/" + $scope.name);
与$location.path("/studentsSearch/" + $scope.name);
更正命名问题,它应该可以工作。
我试过了,它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.