gihan-maduranga
gihan-maduranga

Reputation: 4811

How to create custom modules in AngularJs and bind them in runtime

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.

Upvotes: 1

Views: 47

Answers (1)

Jithu Rajan
Jithu Rajan

Reputation: 452

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(){})

Upvotes: 1

Related Questions