-1

So, I just need something like this.style.backgroundColor = red; how do i write this in angular? $scope.style.backgroundColor didn't work, any other alternatives?

EDIT:

To clarify some things, i need to change the color on CLICK of a <td> element. it was easy to do in JS but now i need to do it dynamically in angular. So yeah, i don't see a way how ng-style can help me?

AlCode
  • 565
  • 1
  • 8
  • 23

1 Answers1

1

Since you're looking at presentation changes, you probably want to make the changes within the view, rather than within the controller.

ng-style will allow you to assign angularjs class objects which can be changed dynamically.

Here's an example from the documentation:

<input type="button" value="set color" ng-click="myStyle={color:'red'}">
<input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>

Edit:

Here's how you can conditionally apply ng-style based upon function calls within your controller:

<td ng-style="{ background-color: clicked ? 'red' : 'black' }">

And, in your controller function:

var $scope.clicked = false; var ChangeColor = function($index){ $scope.clicked = true; }

Note also that you can conditionally apply pre-defined style classes with ng-class, as well (see this related question for examples).

Community
  • 1
  • 1
Beofett
  • 2,388
  • 1
  • 23
  • 37
  • I don't think that this can help me, since i need it to be called in a function. like this: ` var ChangeColor = function($index){ //change color of element[$index] }` – AlCode Apr 28 '15 at 12:28
  • That would have been helpful information to include in your original question... I'll edit to address the new information. – Beofett Apr 28 '15 at 12:33
  • @NeoChrome I've added examples for conditional style application through a controller function call. I hope it helps. – Beofett Apr 28 '15 at 12:42
  • Doesn't work.. and i know why, the $index is always the same for my `` element, the object is created with ng-repeat so yeah.. is there a way to specify the HTML element index ? like $(this).find() in jquery? – AlCode Apr 28 '15 at 12:49
  • Its hard to address without seeing the code, but you should be able to pass the instance from the ng-repeat directly into the function. We're kind of veering into the topic of a different question altogether, but: `` will let you call the function as `$scope.doSomething = function (bar) { ... }` – Beofett Apr 28 '15 at 12:58
  • the function works! it is working but the angular table design is weird. the $index is 0 for the whole row where ever i click it is 0. thats the problem :/ – AlCode Apr 28 '15 at 13:02