简体   繁体   中英

How to add multiple condition in a single class using Angular.js

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 ( ie-place.cstatus==1 and place.cstatus==0 ) for both class. Please help.

使用&&而不是

(i.e-place.cstatus==1 && place.cstatus==0)

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> 

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM