4

I've googled a lot to find an answer to a question which seems fundamental to me, but surprisingly with no success. The official doc left me without answers too. So the simple question is : how to access sibling elements inside the link function of a directive ?

I have a view with an ng-repeat. My directive bind a click on each of the ng-repeat elements :

link: function (scope, element) {
    element.bind('click', function () {
        // how to access element.siblings here ?
...

Thanx.

4
  • 1
    Have you tried element.siblings()? Post complete code of directive Commented Dec 14, 2013 at 15:07
  • why don't you use ng-click? Please show more code. WHat is objective? Commented Dec 14, 2013 at 15:17
  • @Satpal actually the jQlite used in angular.element doesn't have siblings method unless jQuery is loaded Commented Dec 14, 2013 at 15:18
  • I wrote this stackoverflow question 2 days ago where there is some code : stackoverflow.com/questions/20540419/… Commented Dec 14, 2013 at 15:22

1 Answer 1

5

If you are working with jQuery you can use the .siblings() function. If you only have an angular.element, you can access the subsequent siblings with the .next() function.

However, since you are using angularjs, I recommend to rely on the model for such kind of interactions instead of accessing DOM elements the "jQuery" way. If you provide more detail on what you are trying to do, somebody might suggest a better way (from a design perspective) to achieve your goal.

Sign up to request clarification or add additional context in comments.

4 Comments

I don't want to include jQuery. The .next() function is not very elegant for my issue. See my comment above where there is a link to my real problem. Thanx.
Ok, I answered your other question. You should definitely avoid to change classes of sibling elements in this case. There is a reason why angular.element does not support access to siblings.
Agree on the use of model in the directive (so variables + functions on its $scope). You can use a directive's controller and template just as normal, including Angular bindings, interpolation via {{ }}, and other directives like ngClick, ngIf and ngClass. Unless you have a particular reason, like interacting with an external legacy plugin, these tools can mean you don't need to touch the DOM.
next() only matches next sibling...not all siblings

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.