在Javascript/AngularJS中设置嵌套属性
我正在使用AngularJS,我想在我的控制器中设置一些配置变量 例如:在Javascript/AngularJS中设置嵌套属性,javascript,angularjs,angularjs-rootscope,Javascript,Angularjs,Angularjs Rootscope,我正在使用AngularJS,我想在我的控制器中设置一些配置变量 例如: $rootScope.config.showPosts.users = true; $rootScope.config.showPosts.businesses = false; $rootScope.config.showAds.businesses = true; 声明这些“嵌套”属性的正确方法是什么?目前我有: $rootScope.config = []; $rootScope.con
$rootScope.config.showPosts.users = true;
$rootScope.config.showPosts.businesses = false;
$rootScope.config.showAds.businesses = true;
声明这些“嵌套”属性的正确方法是什么?目前我有:
$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;
在设置数组之前,我不必单独声明数组的每个级别,是吗?提前谢谢 您可以使用object Literal:
rootScope.config={
展板:{
用户:是的,
商业:假
},
展示广告:{
商业:是的
}
};
您可以使用object Literal:
rootScope.config={
展板:{
用户:是的,
商业:假
},
展示广告:{
商业:是的
}
};
问题是您试图在数组上设置属性
你写道:
$rootScope.config.showPosts = [];
然后你试着写:
$rootScope.config.showPosts.users = true;
因此,$rootScope.config.showPosts
应该是对象,而不是数组。按如下方式更改代码:
$rootScope.config = {};
$rootScope.config.showPosts = {};
$rootScope.config.showAds = {};
在设置数组之前,我不必单独声明数组的每个级别,是吗
不,您不需要单独声明这些对象,您可以在一个语句中声明整个配置对象
,如另一个答案中所示。问题是您试图在数组上设置属性
你写道:
$rootScope.config.showPosts = [];
然后你试着写:
$rootScope.config.showPosts.users = true;
因此,$rootScope.config.showPosts
应该是对象,而不是数组。按如下方式更改代码:
$rootScope.config = {};
$rootScope.config.showPosts = {};
$rootScope.config.showAds = {};
在设置数组之前,我不必单独声明数组的每个级别,是吗
不,您不需要单独声明这些对象,您可以在一条语句中声明整个配置对象
,如另一条答案所示。太棒了,看起来好多了!太棒了,看起来好多了!