DataGuy
DataGuy

Reputation: 1725

Correct format for routing by Id in AngularJS

I am using the following route in AngularJS:

  .when("/content/:id", {
    templateUrl : "templates/content.html",
    controller : "content"
  })

and the following controller:

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

The controller generates the templateURL in the following format:

#!content/2  //where '2' is a dynamic variable that changes with each menu item

Here is my question:

Is this the correct format for using a variable in the templateUrl?

"/content/:id"

Currently each menu item goes to:

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

But the content isn't changing in the template as needed. BTW, everything works as needed in console.log, which is why Im thinking I have a simple formatting or syntax issue in the way Im formatting the link(s).

Upvotes: 0

Views: 91

Answers (1)

georgeawg
georgeawg

Reputation: 48968

Use the $location service to navigate to a new view:

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

For more information, see


UPDATE

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.

In the content controller, use the $routeParams service to get the parameters for the view:

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

Keep in mind that when ngRoute router changes a view, it destroys the controller and scope for the old view and creates a new controller and new scope for the new view. Any data in the old scope will be lost unless it is saved to a service or passed as a parameter to the new view.

Upvotes: 1

Related Questions