Wednesday, July 8, 2015

Adding Application Constants by removing Magic Strings in Angular applications

Defining App


var myApp = angular.module('myApp', []);

Adding Constants


These constants are used to remove magic string from the application and user application level constants,

myApp.constant('AppConstants', (function () {
    var constants = {};
 
    constants.App = {};
    constants.App.Name = "My Application Name";
 
    constants.LocalStorage = {};
    constants.LocalStorage.profileKey = "profile";
    constants.LocalStorage.clientsKey = "clients";
 
 
    constants.clsProfile = {};
    constants.clsProfile.Email = "Email";
 
    return constants;
 
}())
 
);

Service or controller using Constants

you can use application level constants to reduce magic strings.
(function (ng, app) {
 
    "use strict";
 
    
    app.service("LoginService",function (AppConstants) {

      // using constants

var profileKey = AppConstants.LocalStorage.profileKey;

    this.Login = function (username, password) {                     }              }// end of service function ); // end of service })(angular, myApp );

No comments:

Post a Comment