Angular $routeParams force variable type
Asked Answered
E

3

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

Efficient answered 20/3, 2014 at 10:42 Comment(4)
var id = parseFloat($routeParams.parcId); ?Clinic
Like I said, I want to avoid code in controllersEfficient
Up-voted this question, I have the same problem.Meggy
I can only suggest to use $routeProvider wrapper like ui-router, it supports having typed paramsMoline
B
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.

Botanist answered 8/6, 2018 at 6:26 Comment(1)
Have not tried this, but for me this looks correct answer.Accrete
N
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>
Novelistic answered 23/6, 2015 at 18:11 Comment(0)
S
-3

did you try like this?

parseInt($routeParams.parcId)
September answered 11/5, 2017 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.