我正在尝试根据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
答案 0 :(得分:4)
您尝试访问对象属性而不是数组。
看起来应该是这样的
$scope.home.addnew = function(){
var type = $(event.target).attr("id");
$scope.home[type][0].title;
}
答案 1 :(得分:0)
您确定已将已作为已评论用户之一附加到$ scope的主页。在开始处理之前,$ scope.home需要存在。
答案 2 :(得分:0)
您可以使用数组括号
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);