1

I used to write angularJs related code into one file.(app.js) when the application grows i realized that it is hard to maintain the app.js file due to all things goes to same file.

How it look in past

app.js

var myModule = angular.module(
        'myApp',
        ['ngResource','ui.grid', 'ui.grid.expandable','ui.grid.pagination','ui.grid.expandable'])
        .constant('ENDPOINT_URI', '/api/').factory(
        'AppServices',
        function($resource,ENDPOINT_URI) {


                    function getUrl(path) {
                        return ENDPOINT_URI + path;
                    }

            return {
                User : $resource(getUrl('user/login'), null, {
                    'login' : {
                        method : 'POST'
                    }
                }),

                Test : $resource(getUrl('data/test'), null, {
                    'getResults' : {
                        method : 'GET',
                        isArray : true
                    }

                }),

            };
        });

myModule.config(['$httpProvider','$locationProvider', function($httpProvider,$locationProvider) {
     $locationProvider.html5Mode({
          enabled: true,
          requireBase: false
        });
      $httpProvider.defaults.headers.common["Accept"] = 'application/json';
      $httpProvider.defaults.headers.common["Content-Type"] = 'application/json';
    }]);

myModule.controller('appController', function($scope, AppServices,$window) {
    $scope.user={};
    $scope.user.userName="";
    $scope.user.password="";
    $scope.user.loading=false;
    $scope.user.errorMsg="";
    $scope.user.errorMsgFlag=false;

    $scope.login = function() {


        var userVo = {};
        userVo.userName = $scope.user.userName;
        userVo.password = $scope.user.password;
        AppServices.User.login({}, agentVo).$promise.then(function(data) {
            $scope.agent.errorMsg="";
            $scope.agent.errorMsgFlag=false;
            if(data.apiKey){

                $window.location.assign("/user/ui/test.html");

            }else{
            etc ...
            }

        }, function(error) {


            console.log("Errors in posting Data ..." + "" + error.status);

        });
    };




});

myModule.controller('testController', function($scope, AppServices) {

//Code goes here


});

As a solution i have decided to modularize the application something below.

serviceModule.js

var serviceModule = angular.module(
        'app.services',
        [])
        .constant('ENDPOINT_URI', '/api/').factory(
        'AppServices',
        function($resource,ENDPOINT_URI) {


                    function getUrl(path) {
                        return ENDPOINT_URI + path;
                    }

            return {
                User : $resource(getUrl('user/login'), null, {
                    'login' : {
                        method : 'POST'
                    }
                }),

                TestResult : $resource(getUrl('data/test'), null, {
                    'Test' : {
                        method : 'GET',
                        isArray : true
                    }

                }),

            };
        });

servicesModule.config(['$httpProvider','$locationProvider', function($httpProvider,$locationProvider) {
     $locationProvider.html5Mode({
          enabled: true,
          requireBase: false
        }); 
      $httpProvider.defaults.headers.common["Accept"] = 'application/json';
      $httpProvider.defaults.headers.common["Content-Type"] = 'application/json';
    }]);

loginModule.js

var loginModule = angular.module('user.login',['app.services']);

myModule.controller('loginController', function($scope, AppServices,$window) {
         $scope.user={};
         $scope.user.userName="";
         $scope.user.password="";
         $scope.user.loading=false;
         $scope.user.errorMsg="";
         $scope.user.errorMsgFlag=false;

         $scope.login = function() {


             var userVo = {};
             userVo.userName = $scope.user.userName;
             userVo.password = $scope.user.password;
             AppServices.User.login({}, agentVo).$promise.then(function(data) {
                 $scope.user.errorMsg="";
                 $scope.user.errorMsgFlag=false;
                 if(data.apiKey){

                     $window.location.assign("/user/ui/test.html");

                 }else{
                 etc ...
                 }

             }, function(error) {


                 console.log("Errors in posting Data ..." + "" + error.status);

             });
         };
     });

app.js [NEW]

var mainModule = angular.module(
        'employee',
        ['user.login','ngResource','ui.grid', 'ui.grid.expandable','ui.grid.pagination','ui.grid.expandable']);

//code goes here ...

index.html

        <script src="ui/js/modules/serviceModule.js"></script>
        <script src="ui/js/modules/loginModule.js"></script>
        <script src="ui/js/app.js"></script>
<body ng-app="employee">
<form ng-controller="loginController">
etc...
   </form>
   </body>

When i try to execute above app it throws me User is undefined.This is located in serviceModule as a factory.I am newbie to angularJs and there are lack of docs available in custom modularity in angularJs.Please let me know what i did wrong and guide me correct path.Appreciate your help.

1
  • 1
    Instead of having a lot of modules in separate files you can concatenate or bundle them into one single javascript file. It can be done using gulp concat or you can use a bundler like webpack. Or better, write your app in TypeScript. TypeScript compiler can produce a single transpiled javascript file output Commented Nov 24, 2016 at 6:51

1 Answer 1

1

I think the best way is define all the modules in your app.js itself.

angular.module('app.services',[]);

angular.module('user.login',['app.services']);

angular.module(
        'myApp',
        ['ngResource','ui.grid', 
         'ui.grid.expandable','ui.grid.pagination','ui.grid.expandable','user.login']);

Now create diffrent files for each service.

serviceModule.js

angular.module('app.services').service('AppService',function(){})

loginModule.js

angular.module('user.login').controller('loginController',function(){})
Sign up to request clarification or add additional context in comments.

2 Comments

why we need separate files for each module if we define them in app.js its like code redundant. we can move modues into either app.js or separate js files.
Its all up to the to developer whether he wants to use different files or not. Using the above way you can have separate files each service or controllers which may fall under same module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.