AngularJS constant and value, angularjsconstant
AngularJS can use constant (name, value) and value (name, value) to create services. The same point is that two parameters, name and value, can be accepted. Difference: 1. constant (name, value) can register an existing variable value as a service and inject it into other parts of the application. Here, name is the name of the registered constant, and value is the value or object of the registered constant. Example: (1) When value is:
Angular. module ('myapp '). constant ('apikey', '123 '). controller ('mycontroller', function ($ scope, apiKey) {// you can use apiKey as the constant as above. // use 123123123 as the string value $ 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. The name of value (name, value) is also the service name to be registered. value Returns 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.
Generally, you can use value () to register a service object or function and use constant () to configure data.
Angular. module ('myapp', []). constant ('apikey', '123 '). config (function (apiKey) {// here apiKey will be assigned 123123123 // As set above }). value ('fbid', '123 '). config (function (FBid) {// This will throw an error. Unknown provider: FBid // unable to access this value within the config function });
To sum up, when we want to create a service that only needs to return data, we can use constant (name, value) and value (name, value). However, they have two notable differences:
1. value cannot be injected in config, but constant can
2. The value can be modified, but the constant cannot be modified. Generally, you can directly use constant to configure some frequently used data.