3

I need one help. I need to add multiple condition with AND operator in ng-class using Angular.js. I am explaining my code below.

<div class="mainaccordion_title-width" ng-click="manageCollapseExpand(place, false)">
  <i ng-class="{'fa fa-minus-circle': place.expanded, 'fa fa-plus-circle': !place.expanded }"></i> 
  {{place.root_des}}
</div>

Here I am adding one condition but I need to add another condition (i.e-place.cstatus==1 and place.cstatus==0) for both class. Please help.

1
  • ng-class="{'test': obj.value1 == 'someothervalue' && obj.value2 == 'somethingelse'}" Commented Oct 31, 2017 at 7:07

3 Answers 3

3

Use && instead of and.

(i.e-place.cstatus==1 && place.cstatus==0)
Sign up to request clarification or add additional context in comments.

4 Comments

Can it be like this <div class="mainaccordion_title-width" ng-click="manageCollapseExpand(place, false)"><i ng-class="{'fa fa-minus-circle': place.expanded && place.cstatus==1, 'fa fa-plus-circle': !place.expanded && place.cstatus==0 }"></i>{{place.root_des}}</div>
Yes, just try it. ;)
@subhra my suggestion create a function that returns a string/array of classes and pass it place to it. This way, you will keep your view clean
I dont know but in my editor(i.e-sublime Text) this && showing red mark means some error if I am writing this.
3

As commented before, you can also create a function that takes arguments and return classnames.

Benefit of this approach is, it will keep your view clean and the logic will stay in JS. This will also make it more configurable as you can write a code and share it across multiple elements.

function myCtrl($scope) {
  $scope.place = {
    expanded: false,
    cstatus: 1,
    root_des: 'test'
  }

  $scope.manageCollapseExpand = function(place, seleccted) {
    place.expanded = !place.expanded
  }

  // assuming place should be an array
  $scope.getClasses = function(index) {
    var className = 'fa ';
    if ($scope.place.expanded && $scope.place.cstatus === 1) {
      className += 'fa-minus-circle '
    } else {
      className += 'fa-plus-circle ';
    }

    return className
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller='myCtrl'>
  <div class="mainaccordion_title-width" ng-click="manageCollapseExpand(place, false)">
    <i ng-class="getClasses(0)"></i> 
    {{place.root_des}}

    <p>Classes: {{getClasses(0)}}</p>
  </div>
</div>

1 Comment

This answer is the right one i think using the proper approach.
0

Simply you can conbind condition using &&

<div class="mainaccordion_title-width" ng-click="manageCollapseExpand(place, false)">
  <i ng-class="{'fa fa-minus-circle': place.expanded && place.cstatus==1, 'fa fa-plus-circle': !place.expanded && place.cstatus==0 }"></i> 
  {{place.root_des}}
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.