vincentsty
vincentsty

Reputation: 3231

Angular constant vs javascript constant

Suppose that I have a global constant that need to be accessible in every angular module, what is the advisable approach to declare the constant. I have three approach in my mind but i not sure which to be used.

Appreciate if anyone could point out what is the benefit using Approach 2 compare to Approach 1 in this condition.

Approach 1 (pure js constant):

var jsConstant = {
    constant1: 'constant1',
    constant2: 'constant2'
};

angular.module('mainApp').controller(['$scope', function($scope) {
    $scope.constant1 = jsConstant.constant1;
    $scope.constant2 = jsConstant.constant2;
}]);

Approach 2 (pure angular constant)

angular.module('mainApp').constant('angularConstant', {
    'constant1': 'constant1',
    'constant2': 'constant2'
});


angular.module('mainApp').controller(['myConstant', '$scope', function(myConstant, $scope) {
    $scope.constant1 = angularConstant.constant1;
    $scope.constant2 = angularConstant.constant2;
}]);

Approach 3 (mixture of js and angular constant)

var jsConstant = {
    constant1: 'constant1',
    constant2: 'constant2'
};

angular.module('mainApp').constant('angularConstant", {
    'constant1': jsConstant.constant1;
    'constant2': jsConstant.constant2;
});


angular.module('mainApp').controller(['myConstant', '$scope', function(myConstant, $scope) {
    $scope.constant1 = angularConstant.constant1;
    $scope.constant2 = angularConstant.constant2;
}]);

Upvotes: 2

Views: 448

Answers (2)

Yerken
Yerken

Reputation: 1942

Advisable way is to use constant:

(function(angular, undefined) {
'use strict';

angular.module('myApp.constants', [])

.constant('appConfig', {userRoles:['guest','user','admin']});

})(angular);

Even better way is to inject those values on every build from the server, since most of the time you want to define those values on your server and forget about managing them in other places. For that purpose take a look at ng-constant module for grunt or gulp

Edit Approach 3 is just a messy version of Approach 2 with unnecessary declaration of JS variables outside of Angular modules

Approach 1 is not good, because you those constants are not really reusable. If you have another controller that wants to reuse those values?

Upvotes: 1

tdragon
tdragon

Reputation: 3329

In approach 1 you created a global variable jsConstants which, I believe, is not treated as a good practice - you should avoid creating global constants if possible. Moreover - properties of jsConstants are not really constant - anyone, anywhere can change them. Also, using global constant makes controllers less testable (unit), as they will depend on this global object.

In approach 2 I believe you are not allowed to change these values, so they more act as constant values. You inject them in controllers, so they are still unit-testable.

Upvotes: 0

Related Questions