csvan csvan - 5 months ago 30
AngularJS Question

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?

Answer

A constant can be injected anywhere.

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.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!';
    });
});
Comments