Search code examples
angularjsng-class

Access a div specific variable from inside ng-class


For one of my projects, I have a div with three conditional ng-class, looking like:

<div name="type" ng-class="{'class-one' : stringVariable != "type", 'class-two': stringVariable == "type" && booleanTrue, 'class-three': stringVariable == "type" && !booleanTrue}">My type div.</div>

This works as I want it to run, the problem being when I have several div using the same functionality:

<div name="type" ng-class="{'class-one' : stringVariable != "type", 'class-two': stringVariable == "type" && booleanTrue, 'class-three': stringVariable == "type" && !booleanTrue}">My type div.</div>
<div name="date" ng-class="{'class-one' : stringVariable != "date", 'class-two': stringVariable == "date" && booleanTrue, 'class-three': stringVariable == "date" && !booleanTrue}">My date div.</div>
<div name="name" ng-class="{'class-one' : stringVariable != "name", 'class-two': stringVariable == "name" && booleanTrue, 'class-three': stringVariable == "name" && !booleanTrue}">My name div.</div>

Again, this works but seems inefficient and unwieldy. Every time a div uses this functionality, I end up having to change the variable inside each ng-class' expression, and any future refactoring will be a major pain in the bottom.

I am trying to find a way to define a variable inside the div and then use it inside the ng-class, such as for example something looking like:

<div name="type" ng-class="{'class-one' : stringVariable != $this.name, 'class-two': stringVariable == $this.name && booleanTrue, 'class-three': stringVariable == $this.name && !booleanTrue}">My type div.</div>

Unfortunately, and maybe obviously, this doesn't work.

Is there a way to make this kind of things work?


  • Note1: if it is not possible I will define the classes through the controller, but I would really like to find a way to make it work through ng-class
  • Note2: I would like to avoid using an external directive if possible

Solution

  • In the end, the answer was, as suggested by Tushar, to move all the logic to a separate function, and return ng-class names that way.

    As a result, we have in the template:

    <div ng-class="myMethod("type")">
    

    And in the Controller:

    myMethod : function(stringVariable){
      if (this.$scope.stringVariable == stringVariable) {
        if (this.$scope.booleanTrue) {
          return 'class-two';
        } else {
          return 'class-three';
        }
      } else {
        return 'class-one';
      }
    }