Ryan Ryan - 1 month ago 12
AngularJS Question

Attempting to use controllers with angularjs, error when taking controller code from app.js and putting into a controller file

So I'm trying to play with basic angular code so that I can get a feel for how to create and declare controllers for the project I'm working on. I took some sample code from the angularjs.org controller tutorial and ran into a few issues (turns out I didn't have "./angular.min.js" originally). But I finally got my page to work properly after fixing that.

Then I tried to split the code up so my app.js file could know what controllers to use and I could put the controller code in a separate file (having never made a controller before). After I did this the page gave a console error

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=spicyApp1&p1=Error%…FUsers%2FRDubz%2FDesktop%2Fcontroller%2520test%2Fangular.min.js%3A21%3A179)
and I can't figure out what's wrong. I just want to be able to put the controller code into another file.

app.js with controller code:

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

myApp.controller('SpicyController', ['$scope', function($scope) {
$scope.spice = 'very';

$scope.chiliSpicy = function() {
$scope.spice = 'chili';
};

$scope.jalapenoSpicy = function() {
$scope.spice = 'jalapeño';
};
}]);


app.js without controller code:

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


testController.js

angular.module('spicyApp1.controllers').controller('SpicyController', ['$scope', '$http', function($scope, $http){

$scope.spice = 'very';

$scope.chiliSpicy = function() {
$scope.spice = 'chili';
};

$scope.jalapenoSpicy = function() {
$scope.spice = 'jalapeño';
};

}]);


blank.html

<title>Example - example-controller-spicy-1-production</title>
<script src="./angular.min.js"></script>
<script src="./app.js"></script>
<script src="./testController.js"></script>
</head>
<body ng-app="spicyApp1">
<div ng-controller="SpicyController">
<button ng-click="chiliSpicy()">Chili</button>
<button ng-click="jalapenoSpicy()">Jalapeño</button>
<p>The food is {{spice}} spicy!</p>
</div>
</body>
</html>

Answer

Try this:

File 1:

angular.module('spicyApp1', []);

File 2:

angular.module('spicyApp1').controller('SpicyController', ['$scope', '$http', function($scope, $http){

    $scope.spice = 'very';

    $scope.chiliSpicy = function() {
        $scope.spice = 'chili';
    };

    $scope.jalapenoSpicy = function() {
        $scope.spice = 'jalapeño';
    };

}]);

In your html file

call the file 1, file 2 and so on...