Question

Is there a way to get the index of an directive element in AngularJS? I didn't found anything via the AngularJS documentation and Google. For example I have several directive elements in my DOM like:

<div directive></div>
<div directive></div>
<div directive></div>

Each of them has a unique offsetTop. And I want to write these offsets into a scope variable identified with its index:

app.controller('AppController', [ '$scope', function ($scope) {

    $scope.offsetTopValues = [];

}]);

app.directive('directive', function ($window) {

    return function($scope, element, attrs) {

        $scope.offsetTopValues[index] = element[0].offsetTop;
    };
});

Thanks in advance :)

Was it helpful?

Solution

As far as I know, a directive doesn't have an index in a view like this. However what you could do is something like:

<div directive index="0"></div>
<div directive index="1"></div>
<div directive index="2"></div>

And then in the javascript:

app.controller('AppController', [ '$scope', function ($scope) {

    $scope.offsetTopValues = [];

}]);

app.directive('directive', function ($window) {

    return function($scope, element, attrs) {

        $scope.offsetTopValues[attrs.index] = element[0].offsetTop;
    };
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top