Changing Background Color Of A Div On Ng-click
Solution 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
Solution 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"};
elsereturn {"background-color": "#F0F0F0"};
};
Solution 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.
<divng-controller="MyCtrl">
Hello, {{name}}!
<divng-repeat="item in realName"ng-style='{"background-color": ($even?"white":"#F0F0F0")}'style="cursor:pointer" >
{{item.id}}
{{item.name}}
</div></div>
Solution 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>
Post a Comment for "Changing Background Color Of A Div On Ng-click"