我想访问嵌套ng-repeat的范围。具体点击的项目。我该如何实现?
<div ng-repeat="item in list" ng-click="get(item)">
<div ng-repeat="book in books" ng-click="get(book)">
{{book.name}}
</div>
</div>
和控制器
$scope.get = function(item){
console.log(item);
};
我只能获得项目范围,如何获得书籍范围?如果我同时应用这两个功能,则会触发这两个功能,我只想要单击的项目。
示例
$scope.json = {
"data": {
"books": [
{
"id": "1",
"name": "Tom",
"pub": "Cruise",
"photo": ".jpg",
"topics": [
{
"id": "1",
"pages": "31"
},
{
"id": "2",
"pages": "300"
}
]
},
{
"id": "2",
"name": "Maria",
"pub": "Sharapova",
"photo": ".jpeg",
"topics": [
{
"id": "1",
"pages": "321"
},
{
"id": "2",
"pages": "500"
}
...
]
}
]
}
}
它可以嵌套得更多。
<div ng-repeat="book in json.data.books" ng-click="get(book)">
<div><bold>{{book.name}}</bold></div>
<div ng-repeat="topic in book" ng-click="get(topic)">
{{topic.pages}}
</div>
</div>
它给我这样的结果,
Tom
31
300
Maria
321
500
现在,如果我单击31,则仅需要使用
主题对象 function get(topic){
console.log(topic);
}
console:
{
"id": "1",
"pages": "31"
}
如果我单击“汤姆”,则需要本书的范围
function get(book){
console.log(book);
}
结果应该像这样
{
"id": "1",
"name": "Tom",
"pub": "Cruise",
"photo": ".jpg",
"topics": [
{
"id": "1",
"pages": "31"
},
{
"id": "2",
"pages": "300"
}
]
}
答案 0 :(得分:0)
将ng-click
移动到内部元素:
<div ng-repeat="book in json.data.books">
<div ng-click="get(book)"><b>{{book.name}}</b></div>
<div ng-repeat="topic in book.topics">
<div ng-click="get(topic)">{{topic.pages}}</div>
</div>
</div>
正在运行的演示:demo
答案 1 :(得分:0)
您可以创建如下函数:
function get(topic, refItem){
console.log(topic);
if (refItem) {
console.log(refItem);
//or console.log(JSON.stringify(refItem);
}
}
<div ng-repeat="book in json.data.books" ng-click="get(book)">
<div><bold>{{book.name}}</bold></div>
<div ng-repeat="topic in book" ng-click="get(topic, book)">
{{topic.pages}}
</div>
</div>
或者您可以创建2个或更多这样的函数:
function getBook(book){
console.log(book);
}
function getTopic(topic, book){
console.log(topic);
console.log(book);
}
<div ng-repeat="book in json.data.books" ng-click="getBook(book)">
<div><bold>{{book.name}}</bold></div>
<div ng-repeat="topic in book" ng-click="getTopic(topic, book)">
{{topic.pages}}
</div>
</div>