【问题标题】:How to apply multiple styles based on multiple conditions in ng-style directive?如何在 ng-style 指令中根据多个条件应用多种样式?
【发布时间】:2017-10-27 21:33:13
【问题描述】:

在 Angular 中,我需要根据不同的条件应用不同的样式属性,但它不能以这种方式工作,我只能通过条件表达式应用 2 个条件。

<div ng-style="
    (status=="up")  ?{'background-color':'green' ,'color':'green'}
    (status=="down")?{'background-color':'red'   ,'color':'red'}
    (status=="idle")?{'background-color':'yellow','color':'yellow'}
    (status=="")    ?{'background-color':'grey'  ,'color':'grey'}
">

如果您知道任何方法将属性传递给返回样式 obj 的 ng-style 函数的函数会更好,就像下面这样奇怪地不起作用!

$scope.styleFn(status,attr) {
        (status=="up")  ?{attr:'green'}
        (status=="down")?{attr:'red'}
        (status=="idle")?{attr:'yellow'}
        (status=="")    ?{attr:'grey'}
}

<div ng-style="styleFn('up','background-color')">

【问题讨论】:

    标签: javascript css angularjs ng-style


    【解决方案1】:

    您也可以使用 ng-class。

    function DemoCtrl($scope) {
        $scope.status = 'up'
    }
    .green {
        color: green;
        background-color:green;
    }
    .red {
        color: red;
        background-color:red
    }
    .yellow {
        color: yellow;
        background-color:yellow;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app>
        
        <table ng-controller="DemoCtrl">
            <tr ng-class="{'green': status == 'up','red':status== 'down' ,'yellow': status== 'idle' } ">
                <td style="color:white;">Your status is {{status}}</td>
            </tr>
        </table>
    </div>

    【讨论】:

      【解决方案2】:

      是的,您可以使用函数来指定更复杂的条件。

      var style = {
        'up': {'background-color':'green' ,'color':'green'},
        'down': {'background-color':'red' ,'color':'red'},
        'idle': {'background-color':'yellow' ,'color':'yellow'},
        'default': {'background-color':'grey'  ,'color':'grey'}
      }
      
      $scope.applyStyle = function(status) {
          //the status is the key to get the target style
          return status ? style[status] : style['default']; 
      )};
      

      然后是模板

      <div ng-style="applyStyle(status)"></div>
      

      【讨论】:

      • 没错,但是如何将属性传递给函数并生成自定义样式?它的工作并不奇怪。
      • 只需将属性传递给函数(up、down、idle 或空字符串),函数就会将正确的样式应用于元素。
      • 请再次检查我的问题。状态很好, attr 不起作用。这就是奇怪的部分。例如,如果您通过 'color' 它确实返回 {'color': '#ff0000'} 但不会显示在 DOM 中。
      • 三元运算符甚至必须有 : 才能成为完整的表达式(参见此处: (status=="up") ?{attr:'green'})。其中的一部分,为什么你需要一个 attr 参数?光有地位还不够吗?
      • 没有边框/颜色/背景/...应该改变。
      猜你喜欢
      • 2017-04-27
      • 2020-04-14
      • 2013-08-07
      • 1970-01-01
      • 2021-06-23
      • 2021-01-01
      • 2010-09-06
      • 1970-01-01
      相关资源
      最近更新 更多