wootscootinboogie
wootscootinboogie

Reputation: 8695

Angular controllers in own files, undefined is not a function

I'm refactoring some angular code and I want to separate things by type (controllers in a controllers folder, etc.).

I have two controllers and an app.js file. Why am I getting, and what does this undefined is not a function mean (I get an error in the console from both of my separate controller files)

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

controllers
app.module('myApp.controllers').controller('DocumentController',function($scope){
    $scope.message = "This is the message from Document controller";
})
//
app.module('myApp.controllers').controller('MyController', function ($scope) {
    $scope.message = "This is the message from My Controller";
})

HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="lib/jquery-1.9.1.js"></script>
    <script src="lib/angular-1.2.js"></script>
    <script src="app.js"></script>
    <script src="controllers/MyController.js"></script>
    <script src="controllers/DocumentController.js"></script>
</head>
<body>

    this is from the index.html page
    <div ng-controller="MyController">
        {{message}}
    </div>
<script>

</script>
</body>
</html>

Upvotes: 0

Views: 254

Answers (1)

rob
rob

Reputation: 18513

You need to declare the 'myApp.controllers' module before you can use it. To declare it you need to pass an array of dependencies into angular.module. Try changing app.js to this:

app.js

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

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

controllersApp.controller('DocumentController',function($scope){
    $scope.message = "This is the message from Document controller";
})

controllersApp.controller('MyController', function ($scope) {
    $scope.message = "This is the message from My Controller";
})

Upvotes: 1

Related Questions