Reputation: 83
Hello,
I have made a custom html directive using AngularJS to plot data that I get from a HTTP request.
I've run into an issue where I can't access the $index property of ng-repeat to select the relevant data sets in the returned data to plot.
My code looks like this:
<div ng-controller="AppCtrl">
<form class="sidebar" ng-submit="getData()">
//some selection method
<button type="submit">Select</button>
</form>
</div>
<chart ng-if="data" ng-repeat="item in data" id="{{ $index }}" val="data"></kpi-chart>
getData() returns an object array called "data" containing the measurements I'm interested in plotting in a nested object.
app.directive('chart', function () {
//setup of initial object
return {
restrict: 'EA',
terminal: true,
scope: {
val: '='
},
link: function (scope, element, attrs) {
// Setup of SVG object on page
var orig = newVal[$index];
I want this orig, here at the end, to refer to the $index from ng-repeat above to make it plot graphs with the correct data, with a 1 graph to 1 data set ratio.
How can I make the ng-repeat $index value avaliable to the directive so that it knows which data set to access?
Upvotes: 2
Views: 1132
Reputation: 136144
You need to use attrs.$observe
to get the value of {{$index}}
which will put watch on interpolation value.
Code
attrs.$observe('id', function(newVal, oldVal){
if(newVal) {
console.log("Index of ng-repeat ", newVal)
}
})
Another alternative way would be you could have another variable inside isolated scope that can have index value.
Markup
<chart ng-if="data" ng-repeat="item in data"
id="{{$index}}" index="{{$index}}" val="data">
</chart>
Code
scope: {
val: '=',
index: '@'
},
Then you could have scope.index
inside you link function would give an access to the index of ng-repeat
.
Upvotes: 2
Reputation: 5082
You can use attrs:
link: function (scope, element, attrs) {
var ind = attrs['id'];
var orig = newVal[ind];
Upvotes: 1