Thursday, 14 September 2017

constant in angular JS

Constant in angular JS :
Constant is an object in angular JS.By using the constant we can make the required or re-useble values to be appear globally in application level even.Constant object can also act as like the dependency injection.In simple we can say as like the Constant in angular JS will acts as like service.

Look of constant :
 var app = angular.module('app', []);
     app.constant('valueis',20);

From the above we can observe that the module "app" is set to dbe registered with the "constant" object with holding the "valueis" variable with its value 20.
In constant object we can define any type of data like string, int, array, object.

Look of constant with object :
var app = angular.module('app', []);
 app.constant('user', {
            userid: 1,
            username: 'Hari',
            usersal: 20000
        });
 app.controller('appCtr2', function ($scope,user) {
            $scope.name= user.username;
        });

<div ng-controller="appCtr2">
      User Name is : {{name}}
    </div>

The constant object can be used like a configure file where we can register all our constant values related to the application.

The main thing that can make or advantegeous way with the constant is that, the constant values or its object cannot allowed to change in angular.We can register the constants in multiple controllers.

Differences between constant and value object :
constant's value can not be change where as value's data can be change.
constant can be injected any where where as value can be injected in controller, service, factory but can't be injected in config.

No comments:

Post a Comment