在AngularJS中使用ng-class无法正常工作

时间:2018-01-26 13:53:10

标签: angularjs

我有一个表格,在输入时会检测到信用卡类型。

卡的类型位于“paymentForm.cardNumber。$ ccEagerType”字段中,我可以使用以下方式显示:

Devices and Simulators

如果我在表单中使用{{paymentForm.cardNumber.$ccEagerType|lowercase}} --> 'visa', 'maastercard'.... ,那么效果很好。

但我想用

ng-class="'visa'"

这不起作用。

我做错了什么?

ng-class="'{{paymentForm.cardNumber.$ccEagerType|lowercase}}'"

// CSS

<form class="form-horizontal" role="form" name="paymentForm" novalidate>
    <div class="form-group">
                <label class="col-sm-3 control-label" for="card-number">Card</label>
                <div class="col-sm-6">
                  <input type="text" class="form-control input-lg"  
                  ng-class="'visa'" ng-model="card.number" cc-number cc-eager-type
                  name="cardNumber" ui-credit-card-mask id="cardNumber" placeholder="Cartao Visa, Mastercard e Discover">
                </div>
    </div>
</form>

2 个答案:

答案 0 :(得分:2)

你不需要ng-class,只需直接输入课堂:

<form class="form-horizontal" role="form" name="paymentForm" novalidate>
    <div class="form-group">
        <label class="col-sm-3 control-label" for="card-number">Card</label>
        <div class="col-sm-6">
        <input type="text" class="form-control input-lg {{paymentForm.cardNumber.$ccEagerType|lowercase}}" ng-model="card.number" cc-number cc-eager-type
            name="cardNumber" ui-credit-card-mask id="cardNumber" placeholder="Cartao Visa, Mastercard e Discover">
        </div>
    </div>
</form>
如果你有类似的东西,

ng-class很有用:

<div
    ng-class="{
        'even': $even && someOtherConditions,
        'odd': $odd && someOtherConditions
    }">
    ...
</div>

答案 1 :(得分:0)

你可以用两种不同的方式来做。

作为带有语句的预定义字符串:

<div ng-class="{'green': class === 'green', 'red': class === 'red'}">class: {{class}}</div>

或者您直接使用范围支柱:

<div ng-class="class">class: {{class}}</div>

&#13;
&#13;
function TestCtrl($scope) {
  $scope.class = 'red';

  $scope.switch = function() {
    if($scope.class === 'green') {
    	$scope.class = 'red';
    } else {
    	$scope.class = 'green';
    }	
  };
}
&#13;
.green {
  color: green;
}
.red {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="TestCtrl">
    <div ng-class="{'green': class === 'green', 'red': class === 'red'}">class: {{class}}</div>
    <div ng-class="class">class: {{class}}</div>
    <button ng-click="switch()">Switch</button>
  </div>
</div>
&#13;
&#13;
&#13;