简体   繁体   English

在Angular控制器中定义常数的最佳方法是什么?

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

I currently put my constants on the $scope. 我目前将常量放在$ scope上。 I don't feel like this is the best way to do it as anyone can access the scope with their JS console. 我觉得这不是最好的方法,因为任何人都可以使用其JS控制台访问范围。

What is the best method to define constants in Angular? 在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): 只需在controller回调中将其设为变量(如果使用TypeScript或ES2015 + JavaScript,则将其设为const ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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