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>
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With