ng-class在条件下使用变量中的类

时间:2017-02-21 15:05:17

标签: angularjs ng-class

我正在使用一个指令,并希望以某种方式使用ng-class,我可以在一定条件下输出多个类(存储在变量中)。

<div ng-if="showIcons" ng-class="{state.icon: showIcons}"></div>
$scope.state = { 
    icon: 'icon-cross-outline color-brand-danger'
};

不幸的是,这不起作用。

2 个答案:

答案 0 :(得分:2)

ng-class中使用三元运算符,您可以尝试以下操作吗?

<div ng-if="showIcons" ng-class="showIcons ? state.icon : null"></div>

Demo on Plunker

答案 1 :(得分:0)

您可以通过将函数绑定到ng-class来查看我的plnker

来执行更复杂的操作

JS:

var app = angular.module('hey', []);

app.controller('TheController', [function () {
  this.title = "hey"
  this.shouldApply = true;

  this.canApplyClass = function () {
    if (this.shouldApply == true) {
      return 'happy sad other';
    }

    return '';
  }
}]);

HTML:

<body ng-app="hey">
  <div ng-controller="TheController as c">
    <h1 ng-class="c.canApplyClass()">{{c.title}}</h1>  
  </div>
</body>

我更喜欢这种方法,因为你可以使功能变得复杂 - 甚至可以访问其他服务。