Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js modular controller "undefined" when using $routeParams

Tags:

angularjs

the following returns an error in the console "ReferenceError: ThingCtrl is not defined"

var myApp = angular.module('myApp', []);

myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
    when('/things', {templateUrl: 'partial.html', controller: ThingCtrl}).
    when('/things/:id', {templateUrl: 'detail.html', controller: ThingCtrl}).
otherwise({redirectTo: '/things'});
 }]);

myApp.controller('ThingCtrl', ['$scope', '$routeParams', function($scope, $routeParams) {
$scope.thing = [
    {
        'title':'first thing',
        'first':'one',
        'second': 'two',
        'third': 'three'
    }
];

}]);

however it works fine when the controller is defined like:

function ThingCtrl($scope, $routeParams) {
        $scope.thing = [
    {
        'title':'first thing',
        'first':'one',
        'second': 'two',
        'third': 'three'
    }
  ]
};

Why does it not work using the modular syntax?

like image 409
user1469779 Avatar asked Jan 28 '13 15:01

user1469779


1 Answers

I believe that the issue is here:

when('/things', {templateUrl: 'partial.html', controller: ThingCtrl})

This is telling Angular to point at the ThingCtrl object, which is undefined and causes an error.

Try enclosing the controller name in quotes like this:

when('/things', {templateUrl: 'partial.html', controller: 'ThingCtrl'})

This should allow Angular to properly use dependency injection.

like image 75
jncraton Avatar answered Sep 28 '22 07:09

jncraton