user2732542
user2732542

Reputation: 36

unable to change color using dropdown in angular js

Here is the plunker i am working on.now the problem is i am able to change color in exampple 1 but unable to change color in example 2.
Thanks in Advance.

Upvotes: 1

Views: 986

Answers (1)

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>

Here is a jsFiddle example


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 the Chrome AngularJS extension batarang. But if you run a console.log() you will see the difference.

Upvotes: 2

Related Questions