javascriptangularjsangularjs-rootscope

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.


Solution

  • You can use object litteral:

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