I've been stuck for about a day on a problem that I can't see through.
I have the following code in a users.js.coffee file:
app = angular.module("app", ["ngResource"])
app.config ['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider) ->
$locationProvider.html5Mode(true)
$routeProvider.when('/users/:id', {templateUrl: '/users/:id.json', controller: UserCtrl})
$routeProvider.when('/users/:id/videos', {templateUrl: '/users/:id/videos.json', controller: UserCtrl})
]
app.factory "User", ["$resource", ($resource) ->
$resource("/users/:id", {id: "@id"}, {
show: {method: "GET"},
videos: {method: "GET", isArray:true}
})
]
@UserCtrl = ["$scope", "$location", "$route", "http", "$routeParams", "User", ($scope, $location, $route, $http, $routeParams, User) ->
console.log($location)//LocationUrl {$$parse: function, $$compose: function, $$rewriteAppUrl: function, $$protocol: "http", $$host: "localhost"…}
console.log($route)//Object {routes: Object, reload: function}
console.log($routeParams)//Object {}
]
Why would $routeParams be an empty object? If I call $route.current.params in a view, it shows the appropriate parameters. But not in the controller. What's more, I can't call $route.current.params in the controller, because "current" isn't yet defined.
I had the same problem. The routing won't work if there is no ng-view. Just had a ng-view you'll get your $routeParams.
regards
If you are using an external controller to the routed-to ng-view controller (like a topbar, or page controller), the you'll need to subscribe to the '$routeChangeSuccess' emit message.
The route change success is asynchronous if you aren't the receiving controller. This SO answer gives a more complete answer: $routeParams is empty in main controller
but this is the tldr;
$scope.$on('$routeChangeSuccess', function() {
// $routeParams should be populated here
});
It looks like $routeParams is not available at controller initialization time to controllers outside of those routed via $routeProvider / ng-view. (At least in angular 1.0.8)
If you want to access the route parameters in those outer controllers you can use $location.search().<param_name>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With