Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js - getting access to the params via $route or $routeParams

I have an Controller in which I inject $route and $routeParams but when I go to get the value via

$route.routes.current.params.test ->> current is undefined $routeParams.test ->> test is undefined

Both objects seem to be populated correctly when I use console.log($route) or console.log($routeParams)

I'm baffled. How could the value be there for console.log but fail inside the same controller that I doing the console.log from?

Update: Sample Code

    angular.module('TestApp')
        .controller('TestController', ['$scope', '$http', '$routeParams', '$route',
            function($scope, $http, $routeParams, $route) {
                console.log($routeParams);
                //console.log($routeParams.test);
                console.log($route.current.test);
                //console.log($route.routes);

            }]);
like image 457
BuddyJoe Avatar asked Aug 21 '13 21:08

BuddyJoe


Video Answer


2 Answers

See http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED#routing and https://groups.google.com/d/msg/angular/ib2wHQozeNE/sC3SX3QTyRgJ

In your code, $route and $routeParams are likely being resolved asynchronously. By the time you expand the objects in the console, they have been resolved, but they are not resolved when the controller constructor function runs.

Use $scope.$on('$routeChangeSuccess', function(...) { ... }) in your controller, and try examining the route properties there.

$routeChangeSuccess

like image 79
Mark Rajcok Avatar answered Sep 28 '22 02:09

Mark Rajcok


A little tweak with Chrome Console

I just want to add that this strange behaviour with console is worth paying attention to: it updates the object when you expand it. Say we have:

obj = {}
obj.a = {x: 1} //give it something worth displaying the expand triangle for
console.log(obj)
obj.b = 1
console.log(obj)

In console we'd get:

▶ Object {a: Object}
▶ Object {a: Object, b: 1}

Which displays the difference between those two copies of obj correctly. However when you expand the two, they're no different:

▼ Object {a: Object}
  ▶ a: Object
    b: 1
  ▶ __proto__: Object

▼ Object {a: Object, b: 1}
  ▶ a: Object
    b: 1
  ▶ __proto__: Object

With $route

But at least we could tell from the console that something is updated asynchronously if the one line console is different from its expansion, for instance when the $route with only two key/value pairs:

▶ Object {routes: Object, reload: function}

Expands into three:

▶ Object {routes: Object, reload: function}
  ▶ current: angular.extend.angular.extend
  ▶ reload: function () {}
  ▶ routes: Object
  ▶ __proto__: Object
like image 27
Lucia Avatar answered Sep 28 '22 02:09

Lucia