【问题标题】:In Angular, can I pass a constant to a constant?在 Angular 中,我可以将常量传递给常量吗?
【发布时间】:2015-01-15 07:48:24
【问题描述】:

我可以在角度定义一个常数,它本身取决于传递给它的常数吗? Here's a contrived example:

angular
  .constant("names", ["Bob", "Jane"])
  .constant("friends", ["names", getFriends]);

function getFriends(names) {
  var friends = {};

  names.forEach(function(name) {
    friends[name] = { firstName: name };
  });

  return friends;
}

所以本质上,names 常量定义了一个名称数组,然后我将其传递给一个函数以生成一堆对象字面量。

这段代码肯定行不通 - 但是有没有办法可以完成这种想法?我唯一能想到的就是这样......

var names = ["Bob", "Jane"];

angular
  .constant("names", names)
  .constant("friends", getFriends())
  .controller("myController", MyController);

function getFriends() {
  var friends = {};

  names.forEach(function(name) {
    friends[name] = { firstName: name };
  });

  return friends;
}

...但我试图避免这种情况(我希望在单独的 JS 文件中定义常量)。

注意:我没有为friends 使用工厂的原因是我希望在配置阶段这两个常量都可用。

【问题讨论】:

    标签: javascript angularjs constants


    【解决方案1】:

    你可以在模块的config阶段做一些处理,where constants are available

    angular.module('myModule').constant('names', ['Bob', 'Jane']);
    angular.module('myModule').constant('friends', {});
    
    angular.module('myModule').config(function(names, friends) {
      names.forEach(function(name) {
        // Modifying the friends constant
        friends[name] = { firstName: name };
      });
    });
    

    请注意,虽然您无法更改对象常量所指的内容,但您可以更改对象本身。

    【讨论】:

    • 有趣的方法......虽然感觉它违反了常量的含义!
    【解决方案2】:

    看起来答案是肯定的 - 你不能将常量传递给常量。

    我最终选择了using a provider instead

    angular
        .module("myApp", [])
        .constant("names", ["Bob", "Jane"])
        .provider("friends", FriendsProvider);
    
    FriendsProvider.$inject = ["names"];
    
    function FriendsProvider(names) {
        var self = this;
        self.friends = {};
    
        // ----- 8< -----  
    
        self.$get = [function() {
          return self.friends;  
        }];    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多