简体   繁体   中英

How do i select sibling Elements in AngularJS

I got a 4-5 rows of div ... when i click on any row it should change the selected one and color it as red and rest all to black ... i am using below logic but not working for me giving error as angular.min.js:117 TypeError: angular.element(...).siblings is not a function

Do i need to include jQuery file? Can i do it without including jQuery file?

plz help

 $scope.divClick = function($event){ console.log($event.target); /* below siblings function not working for me*/ angular.element(event.target).siblings().css('color','black'); angular.element(event.target).css('color','red'); }; 
 <div ng-controller="homeController"> <h1>Welcome</h1> <div ng-repeat="x in json" ng-click="divClick($event)"> Name: {{x.Name}}<br/> City: {{x.City}}<br/> Country: {{x.Country}}<br/><br/> </div> </div> 

Set your default color to be black.

   <div ng-repeat="x in json" ng-class="{setRed: $index == value}" ng-click="divClick($index)">

Give CSS style to your class setRed.

Your controller function:

$scope.divClick = function(index){
    $scope.value = index;
};

In general it's bad idea to modify DOM right from your controllers. It's better to use scope or model properties and make decisions what class to apply based on them.

<div ng-repeat="x in json" ng-click="select($index)" ng-class="{'selected': $index == selectedIndex}">
Name: {{x.Name}}<br/>
City: {{x.City}}

Then you just have to update selectedIndex in you click handler

$scope.select = function(x) {
   $scope.selectedIndex = x;
};

Fully working solution is here

https://jsfiddle.net/kvtcw8y6/4/

Other way is to have isSelected property on you model and update it accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM