Skip to content Skip to sidebar Skip to footer

Separate AngularJS Controllers Into Separate Files

I am using Ui-Router with my AngularJS application, and am wondering how I split my angular controllers into different files to make them much more clean. For example: var app = an

Solution 1:

You need to load the files containing your controllers in your HTML before you load the file that declares your application.

<script src="/path/to/angular.js"></script>
<script src="/path/to/controller1.js"></script>
<script src="/path/to/controller2.js"></script>
<script src="/path/to/yourapp.js"></script>

Inside each controller file, you would declare a controller like this:

var Controller = function ($scope) {

}

Controller.$inject = ['$scope'];

Inside your main file after you declare the app variable:

app.controller('Controller', Controller);

Solution 2:

you can write your controller in separate file and just include it in your HTML file after you include your app file

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/Demo.js"></script>
<script src="~/Scripts/DemoController.js"></script>
<title>Demo</title>
</head>
<body>
<div ng-app="demoApp">
    <div ng-controller="demoController">
        <span>{{dummyData}}</span>
    </div> 
</div>
</body>
</html>

code of Demo.js

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

code of DemoController.js

demoApp.controller('demoController', function($scope) {
     $scope.dummyData = "hello from demo app";
});

Post a Comment for "Separate AngularJS Controllers Into Separate Files"