Skip to content Skip to sidebar Skip to footer

How To Have Controllers In Separate File In Angularjs

I look around a bit and didn't find an answer that fit with my current situation. I have a app.js file: 'use strict'; var demoApp = angular.module('demoApp', [ // Dépendances

Solution 1:

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.

varapp= 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

<htmlng-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 --><scripttype="text/javascript"src="app/app.module.js"></script><scripttype="text/javascript"src="app/app.routes.js"></script><scripttype="text/javascript"src="app/components/home/homeCtrl.js"></script><scripttype="text/javascript"src="app/components/home/homeService.js"></script><scripttype="text/javascript"src="app/shared/navigation-bar/navbarDirective.js"></script><scripttype="text/javascript"src="app/shared/navigation-bar/navbarService.js"></script><scripttype="text/javascript"src="app/components/login/loginCtrl.js"></script><scripttype="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

Solution 2:

instead of defining the app as var app = angular.module('myApp', []); use angular.module('myApp', []); var not necessary. Then in separate files like somethingCtrl.js you can define controllers like:

angular.module('myApp')
    .controller('somethingCtrl', ['$scope', function($scope) {
    }]);`  

then you can add the script tags in order on html. start with the module definition first. Use these style guidelines for angular

OPTION 2

define your first module. Then you define various other modules and use them as dependencies like so

index.js:

angular.module('mainApp', ['otherApp']);

other.js

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

This gives you the flexibility to add all of your controllers to one module and all of your directives to another. You can mix the functionality around by using modules as dependencies. Just make sure the mainApp is loaded first in the script tag order.

Solution 3:

This is where requirejs or browserify would help you enormously. However as your question doesn't relate to either of them you can use good ol' JS to accomplish something similar.

Take for example your app.js file. Build in a global config object, then use that when referencing the app name wherever you are. Then it's a case of just changing the app name in the config object to something else without breaking any other components.

var config = {
    app : "myApp"
}

angular.module(config.app, ["ngAnimate"]);

Now a controller in controller.js can use that same config object.

angular.module(config.app)
       .controller("myController", function($scope) { ... }

As long as you load in app.js first you'll have the config object available.

<scriptsrc="/js/app.js"></script><scriptsrc="/js/controller.js"></script>

This isn't pretty and I'd advise you to use browserify or requirejs (or any other alternative) in the future to build out your front end if you want this kind of functionality without the need for horrible global objects/variables.

Solution 4:

Say this is your directory layout:

├── controllers
│   └── home.js
├── directives
└── index.html

You define your controller in home.js like you usually would, and then include it in index.html with:

...
<scriptsrc="./controllers/home.js"></script>
...

P.S.: Using the script tag should be the preferred way to do this, however should you wish to use Require.js, there is a fantastic library angularAMD

Post a Comment for "How To Have Controllers In Separate File In Angularjs"