Ng类有条件

时间:2018-02-21 17:44:16

标签: angularjs ternary-operator ng-class

如果值不为null或为空,我需要有条件地将类应用于div,但我遇到了语法问题。这就是我正在尝试的:

<div ng-repeat="itemTabelNutricional in item.propriedadesNutricionais.obrigatorias">
  <div class="row">
    <div class="col-xs-12 col-lg-3">
      <div class="form-group">
        <label ng-bind-html="itemTabelNutricional.nutrientTypeCode.nome"></label>
      </div>
    </div>
    <div class="col-xs-12 col-lg-3">
      <div class="form-group" ng-class="!!itemTabelNutricional.measurementPrecisionCode ? {'has-error': form.nutricional.itemTabelNutricional.quantityContained.$invalid && form.submitted} : ''">
        <input type="text"
               class="form-control ng-pristine ng-untouched ng-valid ng-valid-maxlength"
               maxlength="255"
               data-toggle="popover"
               data-trigger="hover"
               data-container="body"
               data-content="Informe a quantidade."
               ng-required="true"
               ng-model="itemTabelNutricional.quantityContained" />

      </div>
    </div>
  </div>
</div>

它无法正常工作,因为我仍然得到类,即使值为null或空......任何想法?

2 个答案:

答案 0 :(得分:0)

问题是ng-class需要是字符串还是对象表达式。试试这个:

ng-class="(!!itemTabelNutricional.measurementPrecisionCode && form.nutricional.itemTabelNutricional.quantityContained.$invalid && form.submitted ? 'has-error': '')"

可替换地:

ng-class="{'has-error': (!!itemTabelNutricional.measurementPrecisionCode && form.nutricional.itemTabelNutricional.quantityContained.$invalid && form.submitted)}"

答案 1 :(得分:0)

Ng-class接收一个对象表达式,尝试将条件放在对象中,如下所示:

ng-class="{'has-error': itemTabelNutricional.measurementPrecisionCode && form.nutricional.itemTabelNutricional.quantityContained.$invalid && form.submitted}">