问题
I want to change the background color of a div which already has a backkground color that is white for odd element and grey for even element. Dont know why its not working in Jsfiddle. The div is also having a ng-click which i have not used in JSfiddle example. I want to change the color of the div which is clicked to yellow color. Here is JsFiddle Link....LINK
Basic Code-
<div ng-app="myApp">
<div ng-controller='Ctrl'>
<div ng-repeat='item in jsonContacts' ng-style='{"left":($last?lastX:null)+"px","top":($last?lastY:null)+"px"}'>{{item}}</div>
</div>
</div>
回答1:
Use ngClassOdd and ngClassEven : ng-class-odd="'odd'" ng-class-even="'even'"
.
and add 'odd' and 'even' class to your css file and it should work.
check this upadted version : http://jsfiddle.net/HB7LU/17468/
Edit : I added the change to yellow background
回答2:
You can create a method to control more over your css conditions -
ng-style="set_color(item.id)"
Please check - http://jsfiddle.net/HB7LU/17455/
In Views -
<div ng-repeat="item in realName" ng-style="set_color(item.id)" style="cursor:pointer" >
In controllers -
$scope.set_color = function(id) {
if(id%2 == 0)
return {"background-color": "white"};
else
return {"background-color": "#F0F0F0"};
};
回答3:
Your JsFiddle isn't working because it is using Angular 1.0.1 and I suspect ternary operator support wasn't implemented in expressions at that stage. This update JsFiddle only uses a newer version of Angular and your example works as is then.
Also note, ng-repeat
also has local scope $even
and $odd
properties, similar to $index
that you can use in your calculations, e.g.
<div ng-controller="MyCtrl">
Hello, {{name}}!
<div ng-repeat="item in realName" ng-style='{"background-color": ($even?"white":"#F0F0F0")}' style="cursor:pointer" >
{{item.id}}
{{item.name}}
</div>
</div>
回答4:
There's a couple things to note here:
- Your fiddle is using an ancient version of Angular as mentioned by @Beyers
- You can use ng-class-even and ng-class-odd to set odd/even classes dynamically
- The easiest way to change the class on click is to store the active item in a scope variable and then check against it in an ng-class
See a full working fiddle here: http://jsfiddle.net/HB7LU/17462/
<div ng-controller="MyCtrl">
Hello, {{name}}!
<div class="my-div" ng-repeat="item in realName" ng-class-odd="'oddStyle'" ng-class-even="'evenStyle'" ng-click="doChangeBg(item)" ng-class="{'selectedStyle': activeItem === item.id}">
{{item.id}}
{{item.name}}
</div>
</div>
来源:https://stackoverflow.com/questions/32522270/changing-background-color-of-a-div-on-ng-click