Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-class if else

I'd like to know how to do to make the False ng-class.

page.isSelected(1) is TRUE if the page if the page is selected, else FALSE

<div id="homePage" ng-class="{ center: page.isSelected(1) }"> 

I therefore want you if:

isSelected is TRUE: center

isSelected is FALSE: left

I tried:

<div id="homePage" ng-class="{ page.isSelected(1) 'center : 'left' }"> 

but it doesnt work.

I do not know what I'm doing wrong. Can you help me please?

like image 626
Garu Avatar asked Aug 18 '14 17:08

Garu


People also ask

How do you apply ngClass based on condition?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

Can we use ngClass and class together?

yes , you can do it. Did you try it? What happened? You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

What is ngClass in Angular?

AngularJS ng-class Directive The ng-class directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array. If it is a string, it should contain one or more, space-separated class names.

Can we use NGIF and ngClass together?

javascript - ng-if and ng-class-even/odd doesn't work well together and won't get expected outout - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


2 Answers

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }"> 

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'"> 
like image 162
John Conde Avatar answered Oct 16 '22 03:10

John Conde


You can use the ternary operator notation:

<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'"> 
like image 29
ryeballar Avatar answered Oct 16 '22 03:10

ryeballar