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?
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: {}
});
<mp-show param="id"></mp-show>. Not how I passed the 'id'.I Just want to integrate the good answer from Aditya, as I spend one hour to this issue:
if you have to pass the 'id' as a "<" parameter to your component, you must not use curly braces:
$stateProvider
.state('managementPanels-show', {
url: '/management-panels/show/:id',
template: '<mp-show param="id">{{id}}</mp-show>',
controller: function ($scope, $stateParams){ $scope.id = $stateParams.id; },
data: {},
resolve: {}
});
Note the 'id' passed to "<" 'param' without curly braces. On the other side, "@" parameters remains as param="{{id}}".
Also note: I wrote the controller directly into the state definition, just for the sake of simplicity.
param="id" it depend on how you have scope or binding in mp-show. if it's "@" it should be param="{{id}}" and if it's "=" then it should be param="id". Also the question was about $stateParams.id; (that was the answer)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 }}
Another way to use a custom template and injected parameters is to use templateProvider:
$stateProvider
.state('managementPanels-show', {
url: '/management-panels/show/:id',
templateProvider: function($stateParams){ return '<mp-show>' + $stateParams.id + '</mp-show>'; },
data: {},
resolve: {}
});
All injectables are available, not just $stateParams.
It is important to remember though, that the templateProvider returns a template, and NOT a templateUrl!
If it is desired to use parameters with a templateUrl, it also takes in a function with only parameter as $stateParams(shame):
$stateProvider
.state('managementPanels-show', {
url: '/management-panels/show/:id',
templateUrl: function($stateParams){ return 'templates/mytemplate/' + $stateParams.id; },
data: {},
resolve: {}
});