Reputation: 141
I'm under the impression that ng-repeat creates a new scope for each element in the array/object.
Is it possible to access these new scopes that the ng-repeat creates from the controller? For example if you know the index?
Any help would be much appreciated.
Upvotes: 6
Views: 9988
Reputation: 13329
You can use $parent
as an argument of your function to access these scopes:
<div ng-repeat="item in items">
<div ng-click="doSomethingWithItem(item, $parent)"></div>
</div>
Upvotes: 0
Reputation: 75
When I tried Joy's answer, I got undefined for the item variable at the console. But there is an easier way to do it.
html:
<tr ng-repeat="name in names">
<button class="btn btn-info btn-sm pull-right" ng-click="dealWithItem()">{{name.first_name}}</button>
</tr>
Controller:
$scope.dealWithItem = function () {
console.log(this.name.first_name);
}
this.name will have all of the attributes associated with $scope.names.
Upvotes: 3
Reputation: 9560
Check the console of this demo: JSFiddle.
console.log
the scope, there are two attributes $$childHead
and $$childTail
. They are the first and last child scopes created by ng-repeat
.
After getting the first child scope $$childHead
, you can traverse to get other ng-repeat
scope objects through $$nextSibling
and $$prevSibling
.
Note: these attributes start with
$$
, which indicate that they areprivate
Angular variables. I suppose they are not intended to be used directly.
If you use ng-repeat
like <div ng-repeat="item in items"></div>
, you can use ng-click="dealWithItem(item, $index)"
to pass this item to a function defined in the controller:
$scope.dealWithItem = function (item, index) {
// console.log(item);
}
It works for nested ng-repeat
as well: JSFiddle.
Upvotes: 9