Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $routeParams is blank

Tags:

angularjs

I have a really simple Angular app that I've distilled to the following:

var napp = angular.module('Napp',['ngResource']);

var CompanyCtrl = function($scope, $routeParams, $location, $resource) {
    console.log($routeParams);
};


napp.config(['$routeProvider', function($routeProvider) {
    $routeProvider
    .when('/company/edit/:id', 
      {templateUrl: '/partials/edit', controller: 'CompanyCtrl'}
    );
}]);

and the HTML:

<div ng-controller="CompanyCtrl"></div>

When I log $routeParams, it comes up blank. When I use .otherwise(), it will load whatever I've specified there. Any idea what I'm missing?

like image 721
wesbos Avatar asked Jun 11 '13 18:06

wesbos


2 Answers

You have a couple of errors:

  1. You've specified the controller in two places, both in the view (<div ng-controller="CompanyCtrl"></div>) and in $routeProvider (.when('/company/edit/:id', {templateUrl: '/partials/edit', controller: 'CompanyCtrl'}). I'd remove the one in the view.

  2. You have to register the controller in the module when specifying it in the $routeProvider (you should really do this anyway, it's better to avoid global controllers). Do napp.controller('CompanyCtrl', function ... instead of var CompanyCtrl = function ....

  3. You need to specify a ng-view when you're using the $route service (not sure if you're doing this or not)

The new code:

var napp = angular.module('Napp', ['ngResource']);

napp.controller('CompanyCtrl', function ($scope, $routeParams, $location, $resource) {
  console.log($routeParams);
});

napp.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when('/company/edit/:id',
      {templateUrl: '/partials/edit', controller: 'CompanyCtrl'}
    );
}]);

The template (/parials/edit)

<div> ... </div>

And the app (index.html or something)

... <body> <div ng-view></div> </body>

I've created a working plunker example: http://plnkr.co/edit/PQXke2d1IEJfh2BKNE23?p=preview

like image 166
joakimbl Avatar answered Oct 13 '22 06:10

joakimbl


First of all try this with

$locationProvider.html5Mode(true);

That should fix your starting code. Then adjust your code to support non-pushState browsers.

Hope this helps!

like image 27
vladikoff Avatar answered Oct 13 '22 06:10

vladikoff