B3none
B3none

Reputation: 409

What is the best way to define a constant in an Angular controller?

I currently put my constants on the $scope. I don't feel like this is the best way to do it as anyone can access the scope with their JS console.

What is the best method to define constants in Angular?

var app = angular.module('app', []);

app.controller('calculatorController', function($scope) {
    $scope.values = [];

    $scope.CONSTANTS = {
        ERROR_MESSAGES: {
            NOT_INTEGER: "One of the values input was not a number!"
        }
    };

    $scope.add = function () {
        var calculatedValue = 0;
        for (var i = 0; i <= $scope.values; i++) {
            if (typeof $scope.values[i] === 'string' || $scope.values[i] instanceof String) {
                alert($scope.CONSTANTS.ERROR_MESSAGES.NOT_INTEGER);
            }

            calculatedValue += $scope.values[i];
        }
        return calculatedValue;
    }
});

Upvotes: 1

Views: 1740

Answers (2)

shubham gorde
shubham gorde

Reputation: 175

If you want all the constants at one place, another way is to declare constants as below .

 var app = angular.module('app', []);
  angular.module('AppName').constant('versionConstant', { 
       "versionNum":"1.22"
   });

  // And inject them in your  controller

  angular.module(AppName).controller(ControllerName, ['$scope','versionConstant', 
    function ($scope, versionConstant) {
         var version=versionConstant.versionNum;
    }); 

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074999

Just make it a variable within the controller callback (or a const if using TypeScript or ES2015+ JavaScript):

var app = angular.module('app', []);

app.controller('calculatorController', function($scope) {
    var ERROR_MESSAGES = {
        NOT_INTEGER: "One of the values input was not a number!"
    };

    $scope.values = [];

    $scope.add = function () {
        var calculatedValue = 0;
        for (var i = 0; i <= $scope.values; i++) {
            if (typeof $scope.values[i] === 'string' || $scope.values[i] instanceof String) {
                alert(ERROR_MESSAGES.NOT_INTEGER);
            }

            calculatedValue += $scope.values[i];
        }
        return calculatedValue;
    }
});

(Though that particular kind of constant should probably be loaded from somewhere...)

Upvotes: 1

Related Questions