1

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 :)

1 Answer 1

4

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;
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yes :) ... indeed, declaration is Angulars philosophy, isn't it? Otherwise I have to use ng-repeat in my view. Thanks, that works: link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.