内联如果在angularjs中

时间:2018-06-18 13:04:48

标签: javascript angularjs

<div class="alcohol">
       <img src="~/img/Interaction/alcohol.png" title="Alcohol" />
       <span>{{product.interaction}}</span>
  </div>

如果{{product.interaction}} == 'CAUTION'意味着跨度颜色为红色任何想法?

1 个答案:

答案 0 :(得分:1)

ng-style与条件(三元)运算符一起使用,该运算符检查某些字符串并提供特定样式。这是它的样子:

<span ng-style="product.interaction=='CAUTION' ? {color:'red'} : ''">
  {{product.interaction}}
</span>

(对于 else ,添加白色)

只需扩展else子句

即可
<span ng-style="product.interaction=='CAUTION' ? {color:'red'} : {color:'white'}">
  {{product.interaction}}
</span>

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.product = {};
  $scope.product.interaction = "CAUTION";
  $scope.product.interaction2 = "ANYTHING"; // to show `else` variation
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
  <div ng-app="myApp" ng-controller="myCtrl">

    <div class="alcohol">
      <span ng-style="product.interaction2=='CAUTION' ? {color:'red'} : {color:'white'}">
        {{product.interaction2}}
      </span>
      
      <span ng-style="product.interaction=='CAUTION' ? {color:'red'} : {color:'white'}">
        {{product.interaction}}
      </span>
    </div>

  </div>
</body>
</html>