我正在学习 Angular,所以这是我的测试应用程序:http://enrolin.in/test/#/students
现在我想按名称搜索数据库。所以我创建了返回我所需要的内容的 php。这是PHP:http://enrolin.in/test/login.php?p=fetchbyname&&name=ak您必须将网址中的名称替换为您需要搜索的任何内容。我还创建了一个返回绝对正确结果的部分页面,这是页面: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 :
.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 :
.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);
更正命名问题,它应该可以工作。
我试过了,效果很好。
关于javascript - AngularJS 无法正确路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37565899/