How to Create Separate Angularjs Controller Files

How to create separate AngularJS controller files?

File one:

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

File two:

angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){

}]);

File three:

angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){

}]);

Include in that order. I recommend 3 files so the module declaration is on its own.


As for folder structure there are many many many opinions on the subject, but these two are pretty good

https://github.com/angular/angular-seed

http://briantford.com/blog/huuuuuge-angular-apps.html

How to have controllers in separate file in AngularJS

Angular Structure

When you build an angular app you should separate as much as possible to give your code readability. You should create a module for each page/part of your web app.

Example

Here is an example of this type of structure, I wrote this and use it as a base for angular apps.

app folder

This folder holds all of your components and routes.

routes.js

This file has the states of your project and is its own module

app.js

This file is just the base where you can call all your other modules as dependencies.

var app = angular.module("myApp",   [
'ui.bootstrap',
'ngAnimate',
'myAppRouter',
'myAppHomeCtrl',
'myAppHomeService',
'myAppNavbarDirective',
'myAppNavbarService',
'myAppLoginCtrl',
'myAppLoginService'
]);

You can see all of the different modules written and added here. See the way this is called myApp? well we call that part in the html

<html ng-app="myApp">

components

this will contain things like "home" and "contact" these folders should have everything then need in little self contained html, controllers and services.

controller/module

This is the bit that really answers your question, to add a new module for a controller you do as follows.

angular.module('myAppHomeCtrl', []).controller('homeCtrl', ['$scope', 'homeContent', function($scope, homeContent){

$scope.dataset = homeContent.getContent();
$scope.header = homeContent.getHeader();
$scope.subheading = homeContent.getSubheader();

}]);

service/factory

So you can see that in the module we call a factory, this is also in this folder and looks like this.

angular.module('myAppHomeService', [])

.factory('homeContent', function(){
return {
getHeader: function(){
return "Welcome Human";
},
getSubheader: function(){
return "To Joe's Awesome Website";
},
};
});

Back to index.html

So back in our index we can add all of these modules in <script> tags like this.

<!-- Angular Modules -->
<script type="text/javascript" src="app/app.module.js"></script>
<script type="text/javascript" src="app/app.routes.js"></script>
<script type="text/javascript" src="app/components/home/homeCtrl.js"></script>
<script type="text/javascript" src="app/components/home/homeService.js"></script>
<script type="text/javascript" src="app/shared/navigation-bar/navbarDirective.js"></script>
<script type="text/javascript" src="app/shared/navigation-bar/navbarService.js"></script>
<script type="text/javascript" src="app/components/login/loginCtrl.js"></script>
<script type="text/javascript" src="app/components/login/loginService.js"></script>

In production you will minify all these but you can just call them alll like this whilst in dev.

Conclusion

To conclude I'll do a summery to make sure you have everything you need to get your modules to work

  1. go to your app.js (main angular module) and app the name to it.
  2. go to your components and create the new module
  3. go to the index.html and add your script tag that links to the new module
  4. now you can use the controllers and all the components as you wish

I hope this guid to angular structure helps you. Good Luck

separate AngularJS controller files in Laravel&Angular Project

The second link that you mention is right but keep in mind that you should consider in Laravel & Angular Project is that the

<script src="{{ asset('js/----.js') }}" defer></script>

will provide the link to the public folder. but your the app.js file that you write your angular code located at the resources\assets\js\app.js
then you should create your TaskController.js into the public/js not in the resources\assets\js\.

try this code
app.js

var app = angular.module('LaravelCRUD', [
'myTaskController'
]
, ['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post['X-CSRF-TOKEN'] = $('meta[name=csrf-token]').attr('content');
}]);

Your TaskController.js that located at public/js

angular.module('myTaskController', []).controller('TaskController', ['$scope', '$http', function ($scope, $http) {
}]);

And finally, add your TaskController to your app.blade.php

<script src="{{ asset('path/ to /TaskController.js') }}" defer></script>

Separate AngularJS Controllers Into Separate Files

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";
});

Splitting AngularJS controllers into multiple files

There's an other way to do this. You can make a module for each file and add them to the myApp module, like this:

app.js

var app = angular.module("myApp", ['onsen', 'loginControllers', 'otherController']);

login.js

var login = angular.module("loginControllers", []);
login.controller("LoginController", function($scope, $http)
{
// All the login logic goes here
});

other.js

var other = angular.module('otherControllers', []);
other("OtherController", function($scope, $http)
{
// All the other logic goes here
});

Make sure you have all the scripts added to your index.html.

AngularJS 1.5 Controllers in Separate Files

Use angular.module('mikevarela').controller..... in subsequent files.

angular.module('mikevarela',[]).controller.....

is equivalent to redefining your app. The second param is requires array.

Quoting official angular.module docs

requires
(optional)
!Array.=

If specified then new module is being created. If unspecified then the module is being retrieved for further configuration.

How to separate a component's controller function into a different file?

you can refer the controller from your module like below :

module.component('A', {
templateUrl: 'template.html',
controller: 'YourController'
});

Then in the another file you can define controller with the method.

function() {
'use strict';

angular.module('app').controller('YourController',
YourController);

YourController.$inject = [ '$scope', '$http', '$window',
'$rootScope' ];

function YourController($scope, $http, $window, $rootScope) {
function yourcontrollerfunction() {
}
yourcontrollerfunction();
}
})();

yourcontrollerfunction function will automatically called when controller is loaded. Controller will be loaded when your module is loaded.

Angular can't find my controllers when split into separate files

When you declaring controllers in separate files you need to use this notation:

angular.module('myWebApp.controllers').
controller('StageBarCtrl', function($scope, $window, $location, $http, eventFactory) {
// ...
});

Note, angular.module('myWebApp.controllers') without [] as the second parameter (getter). It means retrieve previously registered module myWebApp.controllers. However, angular.module('myWebApp.controllers', []) (setter) means "create new module myWebApp.controllers", which overwrites anything that has been registered before.

How to define controllers in multiple files - AngularJs

First, you should get rid of the global app variable. This is not necessary. Second, you have to understand the principle of the angular.module() method.

Using angular.module() with two parameters (e.g. angular.module('my-module', [])) would result in setting a new module with its corresponding dependencies. In contrast, when using angular.module('my-module') the corresponding module is looked up internally and returned to the caller (getting).

The means when you first define you application you might just create the following files and structure.

app.js

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

FirstController.js

angular.module('myApp').controller('FirstController', function () {});

SecondController.js

angular.module('myApp').controller('SecondController', function () {});

If you now include these files in your html document in this particularly order (at least app.js has to come first), your application works just fine with two separate controllers in two separate files.

Further readings

I can recommend the AngularJS Styleguide on modules for getting more ideas on this topic.



Related Topics



Leave a reply



Submit