【问题标题】:Apply css style depending on scope variable根据范围变量应用 css 样式
【发布时间】:2015-10-17 19:32:30
【问题描述】:

我正在尝试根据范围变量设置 css 属性。

基本上是这样的:

 <div ng-style="background: filters.area ? #f39c12 : #424242">

或者它应该更像:

<div ng-style="filters.area ? 'background:#f39c12' : 'background:#424242'">

甚至:

<div ng-style="{{filters.area ? 'background:#424242' : 'background:#ff0000'}}">

但以上方法均无效

【问题讨论】:

    标签: javascript html css angularjs ng-style


    【解决方案1】:

    background 值将由三元运算符设置 & 也使用 { & } 而不是 {{}} 插值。

    基本上ng-style 指令要求JSON & 在内部它使用element.css(JSON)

    <div ng-style="{'background' : filters.area ? '#424242' : '#ff0000'}">
    

    【讨论】:

    • 我猜你的意思是没有第一个背景,因为它已经在三元结果中。我有这样的东西:&lt;div class="filterContent" ng-style="{filters.area ? 'background:#f39c12' : 'background:#ff0000'}"&gt; 但它什么也没做,即使我在两个颜色代码之后添加!important;filterContent 类的背景也会保留
    • @Ellone 我在复制粘贴方面做得不好……看看我更新的答案
    【解决方案2】:

    ng-style 指令中的表达式存在一些语法错误。试试这个方法,

    HTML:

    <div ng-controller="MainController">
        <div id="customControl" ng-style="filterarea ? {'background': '#f39c12'} : {'background':'#424242'}"></div>
    </div>
    

    javaScript : (angularjs)

    angular.module("myapp", []).controller("MainController", ["$scope", function($scope){
        $scope.filterarea = false;
    }]);
    

    CSS:

    #customControl{
        width : 100px;
        height : 100px;
        background-color : yellow;
    }
    

    jsFiddle

    【讨论】:

    • 谢谢! ng-style="filters.area ? {'background': '#f39c12'} : {'background':'#424242'}"&gt; 工作得很好!
    【解决方案3】:

    您需要有一对“{}”。使用

    可以轻松修复此代码
    <div ng-style="{filters.area ? 'background:#424242' : 'background:#ff0000'}">
    

    【讨论】:

      【解决方案4】:

      小提琴:http://jsfiddle.net/jpk547zp/3/

      有关 ng 样式检查的进一步帮助:https://docs.angularjs.org/api/ng/directive/ngStyle

      <div ng-app="approvalApp">
          <div ng-controller="SimpleApprovalController" >
              <div ng-style="filters.area ? {'background-color' : '#424242'} : {'background-color' : '#ff0000'}">
                  test data
              </div>
          </div>
      </div>
      

      【讨论】:

        猜你喜欢
        • 2013-03-12
        • 2020-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 2018-11-11
        • 1970-01-01
        • 2014-01-25
        相关资源
        最近更新 更多