AngularJS: Constants vs Values

前端 未结 3 1442
离开以前
离开以前 2020-12-04 11:43

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

3条回答
  •  生来不讨喜
    2020-12-04 11:56

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

提交回复
热议问题