AngularJS 中按 Id 路由的正确格式

Correct format for routing by Id in AngularJS

我在 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 中的一切都按需要工作,这就是为什么我认为我在格式化 link(s) 时遇到简单的格式或语法问题。

使用 $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;
    });
});

有关详细信息,请参阅


更新

just need to figure out the best way to pass index to the content controller so it controls which element of the array is being called.

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