简体   繁体   中英

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;
    }
});

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...)

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;
    }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM