AngularJS中按Id路由的正确格式



我在AngularJS中使用以下路由:

.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]
};     
});
});

控制器以以下格式生成模板URL:

#!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;
});
});

有关更多信息,请参阅

  • AngularJS开发者指南-使用$location服务

更新

只需要找出将索引传递给内容控制器的最佳方式,以便它控制调用数组的哪个元素。

在内容控制器中,使用$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路由器更改视图时,它会破坏旧视图的控制器和作用域,并为新视图创建新控制器和新作用域。旧作用域中的任何数据都将丢失,除非将其保存到服务或作为参数传递到新视图。

最新更新