简体   繁体   中英

Setting nested properties in Javascript / AngularJS

I'm using AngularJS, and I want to set some config vars in my controller.

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 .

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

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