[英]How can I access object dynamically in angularjs?
I am trying to access the object dynamically based on the ng-click.I will have lot's of form with button like this. 我正在尝试基于ng-click动态访问对象。我会有很多这样的带有按钮的形式。
HTML 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>
My Object 我的对象
"home": {
"news": [{
"type": "cd",
"title": "title1",
}],
"allocation": [{
"type": "cd",
"title": "title2",
}],
"create": [{
"type": "cd",
"title": "title3",
}]
.......etc
}
Angularjs Controller 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
}
I am getting error 我遇到错误
Cannot read property 'title ' of undefined
Your trying to access object property instead of array. 您试图访问对象属性而不是数组。
It should look like this 它应该看起来像这样
$scope.home.addnew = function(){
var type = $(event.target).attr("id");
$scope.home[type][0].title;
}
Are you sure that you have attached home to $scope as one of the user already commented. 您确定已将$ scope附加在首页上,其中一位用户已在评论中。 $scope.home needs to exist before you start working on it.
$ scope.home必须存在,然后才能开始使用它。
You may use brackets for array 您可以将方括号用于数组
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.