Sunday, August 17, 2014

Modularizing my AngularJS application

Slowly I'm refactoring My Angular application.
I really like to put general functionality in separate files and services. Not an easy task in Angular, since you really have to get the concept right with modules and dependency injection.

My main application in app.js is dependent on Contracts and Companies.
The Contracts module depends on services that I want to use in all my forms, called frmServices.
In Frmservices I want to use the HTTP Service, for instance to have a more generic delete call that I want to use from wherever I like.

With trail and error the structure now looks like this:

Main app.js (partial)

var ContractsApplication = angular.module('ContractsApp', ['ngRoute','ngResource','Contracts','Companies']);

Company.js (partial)
var CompaniesApp = angular.module('Companies', ['frmServices']);

Form.js (dependent on $http)

var FormApp = angular.module('frmServices', [])                                                                                                                                                                       
.factory("frm", ['$http', function($http) {                                                                                                                                                  
    return {                                                                                                                                                                                                             
        Delete: function(p_Deltext,p_Url,p_Id) {
            var retVal = confirm(p_Deltext);
            if (retVal==true) {
                var httprequest=GloServername + p_Url + "/Delete/" + p_Id;
                $http.delete(httprequest).success(function() {
                    return true;   
                }).error(function(data,status){alert("failure Delete: HTTP code:" + status)});
            return false;

        Update: function() {
            //Do something else here

When you want to use the delete function in the service, do not forget to inject the service in your controller. In this case in the Company.js (the frm injection):

You can then call the delete from within the controller as following:
    if (frm.Delete("Delete ?","RestCompanies",pCompany_id)==true)

Hope this helps. It took me several hours to figure it all out. The nice thing is however you can have a whole hierarchy of dependent modules. Be carfull with your service names however. They have to be unique. There is a lot more refactoring to do, since ultimately I would like to pass a company service to the delete function, that will take care of the delete.

No comments: