Angularjs Constant and enum with example

angularjs enum to string angularjs constant vs value angularjs constant config angularjs constant naming convention angularjs constant function angularjs constant object angularjs constant inject angularjs constant array

As we know the benefit of constant and enum in any other language, we need to it wherever need in our project. But angularjs does not have any enum concept, we will try to create some constants, object to achieve the same goal of enum easily with example. Luckily AngularJS provides a constant service type that can be used for static data that will not change and can be used throughout the application. This can be injected like any other service into any module where it is required.

Let's see the simplest code to declare a constant

var app = angular.module('myApp',[]);
app.constant('Constants', {
    //add all the constants here
}); 

Wherever we need to use this Constants we simply inject and use it, Let add a Roles list of constants

var app = angular.module('myApp',[]);
app.constant('Constants', {
    Roles: {
        admin: 'SYS_ADMIN',
        user: 'SYS_USER',
        guest: 'SYS_GUEST'
    }
}); 

Let's say I want to use this constant into my contact controller then inject 'Constants' and use it like any other object

app.controller('contactCtrl', ['$scope', 'Constants', 
  function ($scope, Constants) {

    $log.log(Constants.Roles['admin']); 

    var role = 'SYS_ADMIN';     
    if(role == Constants.Roles['admin']){
        // Do something
    }
}])

By using this constant service can we create the enum, let's see this with example, suppose we want to create enum of Gender like this in C#

public enum Genter
{
    Male = 1,
    Femate = 2,
    Unknown = 3
}   

The same enum in angular can be created like this:

app.constant('Constants', {
    Roles: { ...},
    Gender: {
        1: 'Male',
        2: 'Female',
        3: 'Unknown'
    }
});

How can we use this Gender enum, It can be used in the same we as we used our Roles constant, see this

var gender = 'Male';
if(gender == Constants.Gender[1]){
    // Do something
}

If you want to use it on view simply put it on the scope $scope.const = Constants; and use it wherever you want in your view

So far it was simple, only the name value or Id value but suppose I have a list of countries with Id, short name and long name an want to access by Id or short name to get the long name then it will be a little bit tricky, let's see what I am talking

app.constant('Constants', {
    Roles: {...},
    Gender: {...},
    Country: [
        { Id: 1, ShortName: 'AR', FullName: 'Argentina' },
        { Id: 2, ShortName: 'CZ', FullName: 'Czech Republic' },
        { Id: 3, ShortName: 'DO', FullName: 'Dominican Republic' },
        { Id: 4, ShortName: 'NZ', FullName: 'New Zealand' },
        { Id: 5, ShortName: 'SA', FullName: 'Saudi Arabia' }
    ]
 });

As you can see the full name have space in some country names, even if we will try to create the enum in C# or any other language, we would need to define the enum name as well as the description.

If want want to use by Id then simply we can use the index be reducing one in the value because index start from zero, which is not the good example but if it can help anyone, like this

var someId = 4;
Constants.Country[someId - 1].ShortName OR
Constants.Country[someId - 1].FullName

But if we want to get the full name by short name then we can use like this:

var shortName = 'NZ';
Constants.Country.filter(function (items) { return items.ShortName === shortName; })[0].FullName

If any value match till then it's good, if not, it will through error, so rest of the code after this line will not execute which we cannot afford in any case.

So what is the better way to use this kind of complicated enum or constant? If you have ever worked on any live project in angularjs, we always have some application level service, right?

We will inject this constant in that service and will create a simple method like find full name by short name or find full name by Id or find short name by id etc.

app.factory('Application', ['Constants', function(Constants){ var service = {};
service.findFullNameById = function(key){ return Constants.Country.filter(function(items) { return items.Id === key; })[0].FullName; };
return service; }]);

Since we already injecting our application service in different controller so no need to inject the Constants any more we can use the application service wherever needed like this

var Id = 2;
if(Application.findFullNameById(Id) == 'Dominican Republic'){
    // Do something
} 

Let us know if you have any challenging structure to use as a constant. There might be some cases where you can get the data from database and use as constant, in that case, better to save those records in local storage as it is and write some useful methods and use them directly form there.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • angularjs
  • constants
  • enum
By Ali Adravi On 02 Sep, 15  Viewed: 40,473

Other blogs you may like

Angularjs powerful paging on table and searching with delay and demo

Paging on table is the basic requirement and most of us look for some grid so it can provide the complete feature of paging and sorting but in Angularjs it is so easy that anyone can achieve it by writing some code. I checked and found most of the available code give the paging feature in for 1 to... By Ali Adravi   On 14 Aug 2015  Viewed: 15,759

Angularjs Cascading Dropdown/Select with demo

Cascading dropdown with angularjs is easier than MVC and ASP.Net. In Angularjs ng-change is the best event to hook the function to get the second dropdown list items. In this article, we will try to fill the state dropdown on selection change of country and then fill the city dropdown on change... By Ali Adravi   On 06 Aug 2015  Viewed: 51,165

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 2

Add/Edid Customer in Modal Popup --- In previous article we discussed how to search, delete and show detail of customer and contact list. In this article we will try to open the modal popup to add new customer and edit an existing customer record. I divided article in two parts because of the... By Ali Adravi   On 29 Jul 2015  Viewed: 18,054

Custom Directives in AngularJS with example and demo

Angularjs custom directives are the common to avoid the duplicate code, it is easy powerful and really nice. There are already too many directive have been created by experts but as a developer we need to write our own to achieve our specific goal. ng-model, ng-if, ng-show, ng-repeat all these are... By Ali Adravi   On 29 Jul 2015  Viewed: 4,088

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 1

Search sort Insert update and delete are the basic features we need to learn first to learn any language, In this article we will try to create these features with Web API, bootstrap modal popup and ui.router. We will use enetity framework code first to save and retrieve data from database. We... By Ali Adravi   On 28 Jul 2015  Viewed: 29,651