AngularJS:常量与值 [英] AngularJS: Constants vs Values
问题描述
据我了解文档,常量和值之间唯一的具体区别是常量可以在应用程序配置阶段使用,而值仅在运行阶段可用.
As far as I understand the documentation, the only concrete difference between a Constant and a Value is that a Constant can be used during the apps config phase, whereas a Value is only available during the run phase.
我很好奇为什么在这种情况下需要值?它们真的只是有限的常量吗?
I am curious as to why Values are needed at all in this case? Aren't they really just limited Constants?
推荐答案
一个常量可以注入到任何地方.
一个常量不能被装饰器拦截,这意味着一个常量的值永远不应该被改变.
A constant can not be intercepted by a decorator, that means that the value of a constant should never be changed.
var app = angular.module('app', []);
app.constant('PI', 3.14159265359);
app.config(function(PI){
var radius = 4;
//PI can be injected here in the config block
var perimeter = 2 * PI * radius;
});
app.controller('appCtrl', function(PI) {
var radius = 4;
// calculate area of the circle
var area = PI * radius * radius;
});
值与常量的不同之处在于值不能注入配置,但可以被装饰器拦截.
Value differs from constant in that value can not be injected into configurations, but it can be intercepted by decorators.
var app = angular.module('app', []);
app.value('greeting', 'Hello');
app.config(function ($provide) {
$provide.decorator('greeting', function ($delegate) {
return $delegate + ' World!';
});
});
这篇关于AngularJS:常量与值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!