if within an ng-class in the angularJS

2

Why can not I do this next check in my ng-class?

setClass(sessao.tipo_2 != 3D ? sessao.tipo_3:sessao.tipo_2)"

According to the short-if logic, this syntax is right?

    
asked by anonymous 28.03.2016 / 22:51

3 answers

3

The short-if is correct. However, ng-class has a different evaluation behavior. You are calling a function ( setClass ) that will not be re-evaluated.

Since Angular works with dirty-checking , you have two possibilities:

  • Populate a variable in the $ scope containing the final value of the class you want to use; or
  • Perform a simple short-if evaluation, with no function call.

Examples below:

function SampleController($scope) {
  
  $scope.sessao = {
    tipo_2: 'D3',
    tipo_3: 'D4'
    }
  
  $scope.variavelDeClasse = $scope.sessao.tipo_3;
 
}
.D3{
  color:red;
  }

.D4{
  color:blue;
  }
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script></head><body><divng-controller="SampleController">
      <div ng-class='variavelDeClasse'>Exemplo do 1º tipo</div>
      
      <div ng-class='sessao.tipo_2 != "D3" ? sessao.tipo_3 : sessao.tipo_2'>Exemplo do 2º tipo</div>
    </div>
  </body>
</html>
    
29.03.2016 / 18:01
1
data-ng-class="{'classeAqui': sessao.tipo_2 != 3D, 'classeAqui':  sessao.tipo_2 == 3D }"

You must enter a configuration JSON for the ng-class where you will pass key: Class value: condition.

Objeto = { key : condição }
    
30.03.2016 / 03:58
0

I do not know if you already got the answer, but the same question appeared to me now and I used it like this:

<div ng-class="minha_variavel > 0 ? 'col-md-6' : 'col-md-12'"></div>
    
10.11.2017 / 18:48