2

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>
RAHUL DEEP
  • 695
  • 3
  • 13
  • 33

4 Answers4

5

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

shaouari
  • 236
  • 1
  • 3
  • Thanx for the help...how to make sure that only one element should be yellow...that is clicked,the other should turn into their normal color... – RAHUL DEEP Sep 12 '15 at 08:47
1

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"};
};
Nesh
  • 2,389
  • 7
  • 33
  • 54
0

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>
Beyers
  • 8,968
  • 43
  • 56
0

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>
Alex Weber
  • 2,186
  • 2
  • 19
  • 27