AngularJS中按Id路由的正确格式
我在AngularJS中使用以下路线:AngularJS中按Id路由的正确格式,angularjs,angular-routing,Angularjs,Angular Routing,我在AngularJS中使用以下路线: .when("/content/:id", { templateUrl : "templates/content.html", controller : "content" }) 以及以下控制器: app.controller('menu', function($scope, $http) { $http.get('api address') .then(function(response) { s
.when("/content/:id", {
templateUrl : "templates/content.html",
controller : "content"
})
以及以下控制器:
app.controller('menu', function($scope, $http) {
$http.get('api address')
.then(function(response) {
scope.navi = response.data.body;
$scope.selectCourse = function(course, index, path) {
location.href=path
$scope.content = response.data.body[index]
};
});
});
控制器以以下格式生成templateURL:
#!content/2 //where '2' is a dynamic variable that changes with each menu item
我的问题是:
这是在templateUrl中使用变量的正确格式吗
"/content/:id"
当前,每个菜单项都会转到:
http://127.0.0.1:5500/index.html#!/content/1
http://127.0.0.1:5500/index.html#!/content/2
http://127.0.0.1:5500/index.html#!/content/3
但模板中的内容并没有根据需要进行更改。顺便说一句,console.log中的所有内容都可以根据需要工作,这就是为什么我认为我在格式化链接时遇到了一个简单的格式或语法问题。使用
$location
服务导航到一个新视图:
app.controller('menu', function($scope, $http, $location) {
$scope.selectCourse = function(course, index) {
̶l̶o̶c̶a̶t̶i̶o̶n̶.̶h̶r̶e̶f̶=̶p̶a̶t̶h̶
$scope.content = $scope.navi[index];
var path = "/content/" + course.id;
$location.path(path);
};
$http.get('api address')
.then(function(response) {
$scope.navi = response.data.body;
});
});
有关详细信息,请参阅
更新 只需要找出将索引传递给内容控制器的最佳方法,以便它控制调用数组的哪个元素 在内容控制器中,使用
$routeParams
服务获取视图的参数:
app.controller('content', function($scope, $http, $routeParams) {
var contentId = $routeParams.id;
var params = { contentId: contentId };
var config = { params: params };
$http.get('api address', config)
.then(function(response) {
$scope.content = response.data;
});
});
请记住,当
ngRoute
路由器更改视图时,它会破坏旧视图的控制器和作用域,并为新视图创建新控制器和新作用域。旧范围内的任何数据都将丢失,除非将其保存到服务或作为参数传递到新视图。其工作方式仍然相同;只需找出将索引传递给内容控制器的最佳方式,以便它控制调用数组的哪个元素。请记住,当ngRoute router更改视图时,它会破坏旧视图的控制器和作用域,并为新视图创建新控制器和新作用域。旧范围中的任何数据都将丢失,除非将其保存到服务或作为参数传递到新视图。请参阅更新以获得答案。内容控制器中添加的$routerParams实现了这一目的。只要我能够将id传递到响应的元素数组中-viola!非常感谢,朋友。这是一个很好的教训。链接的预期输出是什么http://127.0.0.1:5500/content/1???您是否已尝试删除url的第一个斜杠并仅使用“content/:id”
?