Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get route parameter inside template using ui-router?

I have code like this:

$stateProvider
  .state('managementPanels-show', {
    url: '/management-panels/show/:id',
    template: '<mp-show></mp-show>',
    data: {},
    resolve: {}
  });

how can I add :id to the template?

like image 709
jcubic Avatar asked Dec 05 '22 00:12

jcubic


2 Answers

You cannot directly access the :id in template. You need to inject the $stateParams service in your controller and expose the :id property on controller $scope

.controller('YourController', function ($scope, $stateParams){
   $scope.id = $stateParams.id;
})

In your template now you can access id as:

$stateProvider
  .state('managementPanels-show', {
    url: '/management-panels/show/:id',
    template: '<mp-show>{{id}}</mp-show>',
    controller: 'YourController',
    data: {},
    resolve: {}
  });
like image 176
Aditya Singh Avatar answered Feb 24 '23 19:02

Aditya Singh


If you plan to integrate $state and $stateParams often in your templates, it might be useful to add it assign it to $scope or $rootScope. See the following example from the Docs:

angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
});

Now you can interpolate data values on $scope and $rootScope using Angular's double curly bracket notation.

Config:

$stateProvider
    .state('content', {
        url: "/",
        data: {
            title: 'test'
        }
    })

Template:

{{ $state.current.data.title }}

Source: https://github.com/angular-ui/ui-router/wiki/quick-reference#note-about-using-state-within-a-template

like image 38
Lindauson Avatar answered Feb 24 '23 17:02

Lindauson