Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $routeParams force variable type

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

like image 592
Tib Avatar asked Mar 20 '14 10:03

Tib


1 Answers

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.

like image 136
Paras Chhabra Avatar answered Nov 15 '22 20:11

Paras Chhabra