Search code examples
angularjsangular-ui-router

angular.js ui-router pass variable to state url


I am trying to pass parameters to a state in angular.js ui-router like the following:

.state('details', {
    url: '/details/:index',
    templateUrl: 'views/details.html'
})

The index is being passed through an ng-repeat index

 <div ng-repeat="program in programs">
            <h2>{{program.name}}</h2>

            <p>{{program.description || "No Description"}}</p>

            <p><a ui-sref="details({index: $index})">View details »</a></p>
 </div>

my question is how in details.html do i read the index passed in the url of the state?


Solution

  • Inject $stateParams in your controller.

    Example.

    var myapp = angular.module('myapp', ["ui.router"])
    myapp.config(function($stateProvider, $urlRouterProvider){
    
      // For any unmatched url, send to /route1
      $urlRouterProvider.otherwise("/route1/2")
    
      $stateProvider
        .state('route1', {
            url: "/route1/:index",
            templateUrl: "route1.html",
            controller: function($stateParams, $scope) {
                $scope.index = $stateParams.index 
            }
        })
        .state('route2', {
            url: "/route2",
            templateUrl: "route2.html"
        })
    });