What is the best way to conditionally apply a class?

后端 未结 22 2266
感动是毒
感动是毒 2020-11-22 09:12

Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex.

相关标签:
22条回答
  • 2020-11-22 09:39

    If you want to go beyond binary evaluation and keep your CSS out of your controller you can implement a simple filter that evaluates the input against a map object:

    angular.module('myApp.filters, [])
      .filter('switch', function () { 
          return function (input, map) {
              return map[input] || '';
          }; 
      });
    

    This allows you to write your markup like this:

    <div ng-class="muppets.star|switch:{'Kermit':'green', 'Miss Piggy': 'pink', 'Animal': 'loud'}">
        ...
    </div>
    
    0 讨论(0)
  • 2020-11-22 09:40

    Ternary operator has just been added to angular parser in 1.1.5.

    So the simplest way to do this is now :

    ng:class="($index==selectedIndex)? 'selected' : ''"
    
    0 讨论(0)
  • 2020-11-22 09:43

    This is in my work multiple conditionally judge:

    <li ng-repeat='eOption in exam.examOptions' ng-class="exam.examTitle.ANSWER_COM==exam.examTitle.RIGHT_ANSWER?(eOption.eoSequence==exam.examTitle.ANSWER_COM?'right':''):eOption.eoSequence==exam.examTitle.ANSWER_COM?'wrong':eOption.eoSequence==exam.examTitle.RIGHT_ANSWER?'right':''">
      <strong>{{eOption.eoSequence}}</strong> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
      <span ng-bind-html="eOption.eoName | to_trusted">2020 元</span>
    </li>
    
    0 讨论(0)
  • 2020-11-22 09:43

    If you having a common class that is applied to many elements you can create a custom directive that will add that class like ng-show/ng-hide.

    This directive will add the class 'active' to the button if it's clicked

    module.directive('ngActive',  ['$animate', function($animate) {
      return function(scope, element, attr) {
        scope.$watch(attr.ngActive, function ngActiveWatchAction(value){
          $animate[value ? 'addClass' : 'removeClass'](element, 'active');
        });
      };
    }]);
    

    More info

    0 讨论(0)
提交回复
热议问题