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.
The scope property is most probably the most popular one. When using ng-repeat, every block of repeated content has access to a property called $index . This property is a number, and contains the current index of the “loop” ng-repeat is doing: As you can probably guess, this will display next to each task’s name its index in the $ctrl.tasks array.
To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending the range of the repeater by defining explicit start and end points by using ng-repeat-start and ng-repeat-end respectively.
See the MDN page on deletefor more info. ngRepeatwill silently ignoreobject keys starting with $, because it's a prefix used by AngularJS for public ($) and private ($$) properties. The built-in filters orderByand filterdo not work with objects, and will throw an error if used with one.
Special repeat start and end points. To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending the range of the repeater by defining explicit start and end points by using ng-repeat-start and ng-repeat-end respectively.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With