[英]Setting nested properties in Javascript / AngularJS
我正在使用AngularJS,我想在控制器中設置一些配置變量。
例如:
$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;
我不必在設置數組之前分別聲明數組的每個級別,對嗎? 提前致謝。
您可以使用對象雜物:
rootScope.config = {
showPosts: {
users: true,
businesses: false
},
showAds: {
businesses: true
}
};
問題是您試圖在array
上設置property
。
你寫了:
$rootScope.config.showPosts = [];
然后,您嘗試編寫:
$rootScope.config.showPosts.users = true;
因此, $rootScope.config.showPosts
應該是一個object
而不是此處的array
。 像這樣更改代碼:
$rootScope.config = {};
$rootScope.config.showPosts = {};
$rootScope.config.showAds = {};
我不必在設置數組之前分別聲明數組的每個級別,對嗎?
不,您不需要分別聲明這些對象,可以像另一個答案中所示,在一個語句中聲明整個配置object
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.