I want to access scope of nested ng-repeat. Specifically clicked item. How can I achieve this?
<div ng-repeat="item in list" ng-click="get(item)">
<div ng-repeat="book in books" ng-click="get(book)">
{{book.name}}
</div>
</div>
and controller
$scope.get = function(item){
console.log(item);
};
I am able to get only item scope, how can I get scope of book? If I apply both functions, it triggers both functions, I only want clicked item.
Example
$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"
}
...
]
}
]
}
}
It can be more nested.
<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>
It gives me result like this,
Tom
31
300
Maria
321
500
now if I click on 31, I need topics object only using
function get(topic){
console.log(topic);
}
console:
{
"id": "1",
"pages": "31"
}
and if I click on Tom, I need the book scope
function get(book){
console.log(book);
}
result should be like this,
{
"id": "1",
"name": "Tom",
"pub": "Cruise",
"photo": ".jpg",
"topics": [
{
"id": "1",
"pages": "31"
},
{
"id": "2",
"pages": "300"
}
]
}
Move ng-click
to inner element:
<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>
Working demo: demo
You can create a function like this:
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>
or you can create 2 or more function like this:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.