首页 > 解决方案 > AngularJS - 获取.constant中定义的常量的值

问题描述

我有一个 angularJS .constant,它看起来像这样:

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

    angular.module('someModule')
    .constant('MyConstants', {
        VALUE_ONE: 12345,
        VALUE_TWO: VALUE_ONE // it says "VALUE_ONE is undefined"
    });
})(angular);

请注意,当我写 : 时 VALUE_TWO: this.VALUE_ONE,我的测试与味精有关:

类型错误:未定义不是对象(评估“this.VALUE_ONE”)。

如何在 MyConstants 中获取 VALUE_ONE 的值?

标签: angularjsconstants

解决方案


我认为你不能那样做,我不明白你为什么要那样做。如果您希望 VALUE_TWO 依赖于 VALUE_ONE,那么它不是常量,您不应尝试将其包含在常量中。

如果你想拥有一组常量值,包括注册为 CONSTANTS 的其他值,你可以将它定义为 angular.js服务的属性:

 angular.module('someModule') 
.factory('MyService', ['MyConstants', function(MyConstants) {
  return {
    compositeConstant: [MyConstants.VALUE_ONE, 1, 2, 3]; 
  }
}])

推荐阅读