if inside an ng-class in Angularjs

Asked

Viewed 11,314 times

2

because I can’t do that next check on my ng-class?

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

according to short-if logic, that syntax is right not?

3 answers

4

The short-if is correct. However ng-class has a differentiated evaluation behavior. You are calling a function(setClass) which will not be re-assessed.

since Angular works with Dirty-checking, you have two possibilities:

  • Populate a variable in $scope containing the final value of the class you want to use; or
  • perform an evaluation short-if simple, 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>
    <div ng-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>

1

data-ng-class="{'classeAqui': sessao.tipo_2 != 3D, 'classeAqui':  sessao.tipo_2 == 3D }"

You must inform a configuration JSON for ng-class where you will pass Key: Class value: condition.

Objeto = { key : condição }

1

I don’t know if you already got the answer, but I’ve got the same question now and I used it like this:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.