In my Angular app, I have routes like /items/:id
$routeProvider
.when('/items/:id', {
templateUrl: 'views/items.html',
controller: 'ItemCtrl'
})
In ItemCtrl I get :id
with $routeParams.parcId
The problem is it's a string while the value is a number and all my id are numbers.
So how to force the correct type and not having string by default?
ps: I don't want to do var id = Number($routeParams.parcId)
in all my controllers
I did it using the $routeChangeStart event.
In your app.js file, add the following line to the .run function as :-
angular.module('test1App').run(function ($rootScope) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (next.params.hasOwnProperty('id')) {
next.params.id = Number(next.params.id);
}
});
});
Description: On every change of route, it checks if there is a parameter named 'id'. If yes then it changes it to a number.
Hope it helped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With