Detailed explanation of the difference between AngularJS constant and value

  • 2021-07-24 10:00:02
  • OfStack

angularJS is also important for creating services through constant (name, value) and value (name, value).

The same point is that both can accept two parameters, name and value.

Difference:

1. constant (name, value) can register an existing variable value as a service and inject it into other parts of the application. Where name is the name of the registered constant and value is the value or object of the registered constant.

Examples:

(1) When value is a value:


angular.module('myApp') .constant('apiKey','123123123')
.controller('MyController', function($scope, apiKey) {
//  It can be like above 1 Sample use apiKey As a constant 
//  Use 123123123 As the value of a string 
$scope.apiKey = apiKey;
});

(2) When value is an object:


angular.module('myApp') .constant('apiKey',{name:[],age:[],date:[]})
.factory('myFactory',function(apiKey,$scope){
apiKey.name = "lyy";
});

2. name of value (name, value) is also the service name that needs to be registered, and value will return this value as an instance that can be injected.


ngular.module('myApp')
.value('apiKey','123123123'); 

The biggest difference between them is that constants can be injected into configuration functions, but values cannot.

Typically, you can register service objects or functions with value () and configure data with constant ().


angular.module('myApp', [])
.constant('apiKey', '123123123')
.config(function(apiKey) {
//  Here apiKey Will be assigned to 123123123
//  As set above 
})
.value('FBid','231231231')
.config(function(FBid) {
//  This will throw 1 Error, unknown provider: FBid
//  Because in config This value cannot be accessed inside the function 
});

To sum up, we can use constant (name, value) and value (name, value) when we want to create a service that only needs to return data, but there are two significant differences:

1. value cannot be injected into config, but constant can

2. value can be modified, but constant can not be modified. Generally, constant is directly used to configure 1 data that needs frequent use.


Related articles: