Faruk Yazici
Faruk Yazici

Reputation: 2404

ng-class conditional doesn't work

I have an angular directive named fund. The directive is defined as follows.

return{
  restrict: 'E',
  replace: true,
  scope: {
    data: '=',
    cut: '@'
    },
  templateUrl: 'app/directives/partials/fund.jsp'
}

It has a property named cut. If cut is set, I will apply text-cut class, and if not set, no class. The class is as follows in case needed:

.text-cut{
  overflow: hidden;
  text-align: left;
  text-overflow: ellipsis
}

I have tried the using the directive as:

<fund data="myCtrl.fundList" cut="true"></fund>

<fund data="myCtrl.fundList" cut="'true'"></fund>

with following ng-class attributes in the template:

ng-class="text-cut: cut"
ng-class="text-cut: 'cut'"
ng-class="{text-cut: cut}"
ng-class="{text-cut: 'cut'}"
ng-class="text-cut: cut===true"
ng-class="text-cut: 'cut'===true"
ng-class="{text-cut: cut===true}"
ng-class="{text-cut: 'cut'===true}"

But none of these combinations applied text-cut class to my fund directive. Where is the mistake?

Upvotes: 0

Views: 581

Answers (2)

Kentonbmax
Kentonbmax

Reputation: 958

Create a function that returns the string class you want based on some condition. Then call it in your ng-class. As long as the function returns the css you want it should work.

$scope.checkCut = function(){
   if(this.cut != null){
      return 'text-cut';
   }
}

In your directive

 ng-class="checkCut"

Upvotes: 1

hansmaad
hansmaad

Reputation: 18905

You have to quote text-cut. Try

ng-class="{'text-cut': cut}"

Upvotes: 1

Related Questions