Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the *Angular* way to get an elements siblings?

Tags:

What is the idiomatic way to get an elements siblings when it is clicked using AngularJS?

So far I've got this:

<div ng-controller="FooCtrl">     <div ng-click="clicked()">One</div>     <div ng-click="clicked()">Two</div>     <div ng-click="clicked()">Three</div> </div>  <script>     function FooCtrl($scope){         $scope.clicked = function()         {             console.log("Clicked", this, arguments);         };     } </script> 

here's a jQuery implementation as a concrete example:

<div id="foo">     <div>One</div>     <div>two</div>     <div>three</div> </div>  <script>     $(function(){         $('#foo div').on('click', function(){             $(this).siblings('div').removeClass('clicked');             $(this).addClass('clicked');         });     }); </script> 
like image 729
Greg B Avatar asked Aug 13 '13 14:08

Greg B


2 Answers

Use a directive, since you want to traverse the DOM:

app.directive('sibs', function() {     return {         link: function(scope, element, attrs) {             element.bind('click', function() {                 element.parent().children().removeClass('clicked');                 element.addClass('clicked');             })         },     } }); 

<div sibs>One</div> <div sibs>Two</div> <div sibs>Three</div> 

Note that jQuery is not required.

fiddle

like image 93
Mark Rajcok Avatar answered Sep 21 '22 11:09

Mark Rajcok


Here is an angular version of the jQuery sample that you provided:

HTML:

<div ng-controller="FooCtrl">     <div ng-click="selected.item='One'"      ng-class="{clicked:selected.item=='One'}">One</div>     <div ng-click="selected.item='Two'"      ng-class="{clicked:selected.item=='Two'}">Two</div>     <div ng-click="selected.item='Three'"      ng-class="{clicked:selected.item=='Three'}">Three</div> </div> 

JS:

function FooCtrl($scope, $rootScope) {        $scope.selected = {         item:""     } } 

NOTE: You dont strictly need to access DOM for this. However if you still want to then you can write a simple directive. Something like below:

HTML:

<div ng-controller="FooCtrl">     <div ng-click="clicked()" get-siblings>One</div>     <div ng-click="clicked()" get-siblings>Two</div>     <div ng-click="clicked()" get-siblings>Three</div> </div> 

JS:

yourApp.directive('getSiblings', function() {    return {       scope: true,       link: function(scope,element,attrs){          scope.clicked = function () {             element.siblings('div').removeClass('clicked');             element.addClass('clicked');          }       }    } }); 

fiddle

like image 43
AlwaysALearner Avatar answered Sep 20 '22 11:09

AlwaysALearner