Jaimin
Jaimin

Reputation: 811

Angular js ng style not working

<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

Upvotes: 6

Views: 35097

Answers (2)

Tadele Ayelegn
Tadele Ayelegn

Reputation: 4706

for Angular 6, ngStyle can get working as follows

<p [ngStyle]="{'color': 'red'}"> I Read in Red</p>

Upvotes: 2

jnthnjns
jnthnjns

Reputation: 8925

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 = '';
};

Upvotes: 23

Related Questions