最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular js ng style not working - Stack Overflow

programmeradmin1浏览0评论
<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">

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

Thanks in advance

<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

Share Improve this question edited Mar 28, 2017 at 19:53 isherwood 61.1k16 gold badges120 silver badges168 bronze badges asked Aug 30, 2013 at 12:13 JaiminJaimin 8112 gold badges12 silver badges27 bronze badges
Add a comment  | 

2 Answers 2

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

for Angular 6, ngStyle can get working as follows

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

评论列表(0)

  1. 暂无评论