6
<span>Select color : </span>

<select ng-model="myStyle">
    <option value="">none</option>
    <option value="{color:red}">Red</option>
    <option value="{color:'green'}">Green</option>
</select>

<div ng-style="myStyle">

http://plnkr.co/edit/IOHjEGbuOzD4CjwRqIK9?p=preview

In this plunker, example 1 works perfectly fine but in example 2 select color is not working.

Thanks in advance

isherwood
  • 58,414
  • 16
  • 114
  • 157
Jaimin
  • 801
  • 2
  • 12
  • 27

2 Answers2

23

This is actually a simple fix, have myStyle be more of a myColor type of declaration and on ng-style have your {{'color':myColor}} expression:

<select ng-model="myColor">
    <option value="">none</option>
    <option value="red">Red</option>
    <option value="green">Green</option>
</select>

<div ng-style="{'color':myColor}">
    <p>Text to change color</p>
</div>

There is no need for a ng-change function in THIS instance.

Working Example


Edit, explanation:

Value in select option is not an angular directive so myStyle is being set to literally "{color:'red'}" not the Javascript Object {"color":"red"} that Angular is looking for and can parse in ng-style.

Since the literal value of "{color:'red'}" looks like the object then you will not notice the difference in batarang. But if you run a console.log() you'll see the difference.

Set your example one, then set example 2 to red and change your clearFilter function by adding the two logs and look at the output and you'll see what I mean:

$scope.clearFilter = function () {
    console.log('myStyle1', $scope.myStyle1);
    console.log('myStyle', $scope.myStyle);
    $scope.query = '';
    $scope.orderProp = '';
    $scope.myColor = '';
};
jnthnjns
  • 8,962
  • 4
  • 42
  • 65
  • Thanks, i started with this approach only. In my example, in batarang myStyle was correctly set on change of select but still color was not changing in example 2.. can you tell me why ? – Jaimin Aug 30 '13 at 13:54
2

for Angular 6, ngStyle can get working as follows

<p [ngStyle]="{'color': 'red'}"> I Read in Red</p>
Tadele Ayelegn
  • 4,126
  • 1
  • 35
  • 30