Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create separate AngularJS controller files?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.88k
    Comment on it

    Controllers are used to adding behaviors to $scope object. When you are building a large application,the best practice is to split your controllers into different files according to the purpose that it fulfills. So, you need to follow these very simple steps to create separate AngularJS controller files.

    The proper organization of the folders and files will make your application easier to maintain,comprehensible and enhance the understandability.

    1.The first step is to create a ‘js’ folder that includes all the js folders and files (for eg. controllers,directives,app.js,routes.js,etc).

    2.The second step is to create a file named ‘app.js’. We’ll use it to create and configure the module. It will contain

    var mainApp = angular.module(mainApp,[]);

    3.Third step is to create a file named ‘route.js’. This file contain all the states  in your project and its own module.

    4.Now create a folder named ‘controllers’. This folder will contain all the controller files required for the application.

    5.Create first file named ‘first-example.controller.js’ (you can give name to the controller relevant to the purpose it fulfills like login.controller.js for login functionality).

    mainApp.controller( FirstExampleController", function( $scope ) {
        //write the code over here
    })

    Similarly,you need to create other controllers in separate files.
    Another file ‘second-example.controller.js’.

    mainApp.controller( SecondExampleController", function( $scope ) {
        //write the code over here
    })

    6.You need to include all the files in your ‘index.html’ file in the correct order.
    First load libraries like angular.js. Then app.js and then the controllers with the correct path.

    <script src="js/lib/angular.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers/first-example.controller.js"></script>
    <script src="js/controllers/second-example.controller.js"></script>

    Follow the above steps to create a balanced file structure of an Angular app and create multiple controllers in separate files.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: