简体   繁体   English

在Javascript / AngularJS中设置嵌套属性

[英]Setting nested properties in Javascript / AngularJS

I'm using AngularJS, and I want to set some config vars in my controller. 我正在使用AngularJS,我想在控制器中设置一些配置变量。

For example: 例如:

 $rootScope.config.showPosts.users = true;
    $rootScope.config.showPosts.businesses = false;
    $rootScope.config.showAds.businesses = true;

What is the correct way to declare "nested" properties like these? 声明此类“嵌套”属性的正确方法是什么? At the moment I have: 目前,我有:

 $rootScope.config = [];
    $rootScope.config.showPosts = []; 
    $rootScope.config.showAds = [];
    // ^ as you can see, I am declaring each key of the array individually :( 
    $rootScope.config.showPosts.users = true;
    $rootScope.config.showPosts.businesses = false;
    $rootScope.config.showAds.businesses = true;

I don't have to declare every level of the array individually before I set it, do I? 我不必在设置数组之前分别声明数组的每个级别,对吗? Thanks in advance. 提前致谢。

You can use object litteral: 您可以使用对象杂物:

rootScope.config = {
  showPosts: { 
    users: true,
    businesses: false
  },
  showAds: {
    businesses: true
  }
};

The problem is that you are trying to set a property over an array . 问题是您试图在array上设置property

You wrote: 你写了:

$rootScope.config.showPosts = []; 

Then you try to write: 然后,您尝试编写:

$rootScope.config.showPosts.users = true;

So $rootScope.config.showPosts should be an object instead of an array here. 因此, $rootScope.config.showPosts应该是一个object而不是此处的array Change your code like this: 像这样更改代码:

$rootScope.config = {};
$rootScope.config.showPosts = {}; 
$rootScope.config.showAds = {};

I don't have to declare every level of the array individually before I set it, do I? 我不必在设置数组之前分别声明数组的每个级别,对吗?

No you don't need to declare these objects individually, you can declare the whole configuration object in one statement like shown in the other answer. 不,您不需要分别声明这些对象,可以像另一个答案中所示,在一个语句中声明整个配置object

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

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