Search code examples
javascriptangularjsmeteoriron-routerangular-meteor

Equivalent of Iron Router's pathFor in Angular UI Router


In Meteor's Iron Router, we could use pathFor to generate a URL, such as

<a href="{{pathFor 'posts' id=1234}}">View</a>

can generate the URL http://domain.com/posts/1234.

Question: Using Angular's UI Router, is there an equivalent of pathFor?

Such that with the routes defined below, we can generate the URL http://domain.com/posts/1234 by having something similar to {{ pathFor 'posts' id=1234}}.

angular.module('myApp').config(function($stateProvider) {

    $stateProvider
        .state('posts', {
            url: '/posts/:postId',
            templateUrl: 'client/posts/views/post.html',
            controller: 'PostCtrl'
        })

})

Solution

  • You could use :

    <a ui-sref="posts({postId:1234})">View</a>
    

    where posts is the state name.

    See here.

    ADDITIONAL

    To get the value of postId and use it on your controller you can use resolve like this.

    $stateProvider
        .state('posts', {
            url: '/posts/:postId',
            templateUrl: 'client/posts/views/post.html',
            controller: 'PostCtrl',
            resolve: {
                ID : function($stateParams){
                    return $stateParams.postId;
                }
            }
        })
    

    Then inject the ID to your controller.

    .controller('PostCtrl',
        ['$scope', 'ID', function($scope, ID){
            // you now have the access to ID
            $scope.id = ID;
    }])