10

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

Tib
  • 2,553
  • 1
  • 27
  • 46

3 Answers3

1

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.

0

You need to use resolve in routes and update the variable. Then use this resolved variable in controller

<a href="http://plnkr.co/edit/2nXeY325ouqyFtJTLcdq?p=preview"> Example </a>
Sandeep
  • 1,154
  • 10
  • 16
-3

did you try like this?

parseInt($routeParams.parcId)
Sharp
  • 121
  • 1
  • 2
  • 16