lapadets
lapadets

Reputation: 1095

Argument is not a function - AngularJS undefined

I am new to Angular and I am currently trying to build something very simple, but I have a problem I am stuck and I don't understand why is it happening.

I have a small project in Webstorm with Express and npm. Angular is added as a dependency, version 1.5.3. I am also using Jade as a template language. Here is what I have in Plunker http://plnkr.co/edit/qCR420hBgnlcUisSOwgw?p=preview

Also listed below:

doctype html
html(lang='en', ng-app='courses')
head
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1, user-scalable=no')

    script(src='/node_modules/angular/angular.js')
    script(src='/node_modules/angular-resource/angular-resource.js')
    script(src='/node_modules/angular-route/angular-route.js')
    script(src='/javascripts/app.js')
    script(src='/javascripts/controllers.js')
    script(src='/javascripts/services.js')

    title= title
    link(rel='stylesheet', ref='//netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css')
    link(rel='stylesheet', href='/stylesheets/style.css')
body(ng-controller='CoursesListController')
    nav.navbar.navbar-inverse.navbar-fixed-top(role='navigation')
        div.navbar-header
            a.navbar-brand(href='#/courses')=title
    div.container
        div(ng-view)

My app.js:

angular.module('courses', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/courses', { templateUrl: 'partials/list.html', controller: CoursesListController })
        .when('/course/:courseId', { templateUrl: 'partials/item.html', controller: CourseItemController })
        .when('/new', { templateUrl: 'partials/new.html', controller: CourseCreateController })
        .otherwise({ redirectTo: '/courses' });
}]);

My controllers.js

function CoursesListController($scope, $routeParams, Course) {
    $scope.courses = Courses.query();
}

And my services.js:

angular.module('courseServices', ['ngResource']).factory('Course', function 
($resource) {
    return $resource('courses/:courseId', {}, {
        query: {method: 'GET', params: {courseId: 'courses'}, isArray: true}
    })
});

The error I get is:

angular.js:13294 Error: [ng:areq] Argument 'CoursesListController' is not a function, got undefined

And I not sure why. Besides, maybe some tips would be useful you think such a structure/separation makes sense?

Upvotes: 0

Views: 171

Answers (1)

Aides
Aides

Reputation: 3673

This is a loading order issue.

Basically you first load app.js which tries to register the function that is not loaded yet.

To fix this just move the script(src='/javascripts/app.js') beneath the other includes.

Edit: Alternatively there is a whole bunch of alternatives to prevent such issues like RequireJS, Webpack, Grunt, etc.

Upvotes: 2

Related Questions