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

最后都变了- 提交于 2019-12-22 04:55:40

问题


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);

            }]);

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/18368262/angular-js-getting-access-to-the-params-via-route-or-routeparams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!