![](/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.