![](/img/trans.png)
[英]How can I access the content of a dynamically created object tag in jquery?
[英]How can I access object dynamically in angularjs?
我正在嘗試基於ng-click動態訪問對象。我會有很多這樣的帶有按鈕的形式。
HTML
<button type="button" id="news" ng-click="home.addnew()">Update</button>
<button type="button" id="allocation" ng-click="home.addnew()">Update</button>
<button type="button" id="create" ng-click="home.addnew()">Update</button>
我的對象
"home": {
"news": [{
"type": "cd",
"title": "title1",
}],
"allocation": [{
"type": "cd",
"title": "title2",
}],
"create": [{
"type": "cd",
"title": "title3",
}]
.......etc
}
Angularjs控制器
$scope.home.addnew = function(){
var type = $(event.target).attr("id");
$scope.home.news.title; // Here how can I access that "news","allocation","create" Dynamically
$scope.home.type.title // I have tried like this
}
我遇到錯誤
Cannot read property 'title ' of undefined
您試圖訪問對象屬性而不是數組。
它應該看起來像這樣
$scope.home.addnew = function(){
var type = $(event.target).attr("id");
$scope.home[type][0].title;
}
您確定已將$ scope附加在首頁上,其中一位用戶已在評論中。 $ scope.home必須存在,然后才能開始使用它。
您可以將方括號用於數組
var dynamicType ='news';
var obj ={"home": {
"news": [{
"type": "cd",
"title": "title1",
}],
"allocation": [{
"type": "cd",
"title": "title2",
}],
"create": [{
"type": "cd",
"title": "title3",
}]
}};
console.log(obj.home[dynamicType][0].title);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.