AngularJS toggle class using ng-class - javascript

I am trying to toggle the class of an element using ng-class
<button class="btn">
<i ng-class="{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}"></i>
</button>
isAutoScroll():
$scope.isAutoScroll = function()
{
$scope.autoScroll = ($scope.autoScroll) ? false : true;
return $scope.autoScroll;
}
Basically, if $scope.autoScroll is true, I want ng-class to be icon-autoscroll and if its false, I want it to be icon-autoscroll-disabled
What I have now isn't working and is producing this error in the console
Error: Lexer Error: Unexpected next character at columns 18-18 [?] in expression [{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}].
How do I correctly do this?
EDIT
solution 1: (outdated)
<button class="btn" ng-click="autoScroll = !autoScroll">
<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
</button>
EDIT 2
solution 2:
I wanted to update the solution as Solution 3, provided by Stewie, should be the one used. It is the most standard when it comes to ternary operator (and to me easiest to read). The solution would be
<button class="btn" ng-click="autoScroll = !autoScroll">
<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>
</button>
translates to:
if (autoScroll == true) ? //use class 'icon-autoscroll' : //else use 'icon-autoscroll-disabled'

How to use conditional in ng-class:
Solution 1:
<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
Solution 2:
<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>
Solution 3 (angular v.1.1.4+ introduced support for ternary operator):
<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>
Plunker

As alternate solution, based on javascript logic operator '&&' which returns the last evaluation, you can also do this like so:
<i ng-class="autoScroll && 'icon-autoscroll' || !autoScroll && 'icon-autoscroll-disabled'"></i>
It's only slightly shorter syntax, but for me easier to read.

Add more than one class based on the condition:
<div ng-click="AbrirPopUp(s)"
ng-class="{'class1 class2 class3':!isNew,
'class1 class4': isNew}">{{ isNew }}</div>
Apply: class1 + class2 + class3 when isNew=false,
Apply: class1+ class4 when isNew=true

<div data-ng-init="featureClass=false"
data-ng-click="featureClass=!featureClass"
data-ng-class="{'active': featureClass}">
Click me to toggle my class!
</div>
Analogous to jQuery's toggleClass method, this is a way to toggle the active class on/off when the element is clicked.

autoscroll will be defined and modified in the controller:
<span ng-class= "autoscroll?'class_if_true':'class_if_false'"></span>
Add multiple classes based on condition by:
<span ng-class= "autoscroll?'first second third':'classes_if_false'"></span>

I made this work in this way:
<button class="btn" ng-click='toggleClass($event)'>button one</button>
<button class="btn" ng-click='toggleClass($event)'>button two</button>
in your controller:
$scope.toggleClass = function (event) {
$(event.target).toggleClass('active');
}

Related

ng-if doesn't works as expected

I have a buttons array in my model, and an 'ng-if' in the template for each button:
self.aButtons.push({
label: __('Siguiente'),
class: 'btn-moduloAvance',
show: (self.oContrato.definirPago || self.oContrato.horario_definido)
}
});
That's the Html:
<button ng-if="boton.show"
ng-repeat="boton in personaAndContrato.aButtons"
type="button"
ng-class="boton.class"
/>
I know that i'm assigning a boolean to the 'show' property, so it's impossible it changes because it's a simple type.
By the way I'm trying to assign a function to the 'show' property but i'm getting the following error:
self.aButtons.push({
label: __('Siguiente'),
class: 'btn-moduloAvance',
show: function () {
return (self.oContrato.definirPago || self.oContrato.horario_definido);
}
});
Html (edited):
<button ng-if="boton.show()"
ng-repeat="boton in personaAndContrato.aButtons"
type="button"
ng-class="boton.class"
/>
TypeError: v2.show is not a function
at fn (eval at compile (angular.js?version=alpha.1:14539), :4:240)
Some ideas? Does i'm missing or missunderstanding something?
Thanks in advance!
You can't have ng-repeat and ng-if in the same tag if ng-if refer to the inner variable of ng-repeat.
Just split it :
<div ng-repeat="boton in personaAndContrato.aButtons">
<button ng-if="boton.show()"
type="button"
ng-class="boton.class"
/>
</div>
Changing to ng-if="boton.show()" will do.

Change color of specific glyphicon when clicked using Angular

I would like to change the color of the specific glyphicon clicked in my Angular app.
For example when this is clicked:
(in ng-repeat block) <span class="glyphicon glyphicon-thumbs-down" ng-click="downvote(post)" ></span>
When clicked it calls:
$scope.downvote = function(post) {
posts.downvote(post);
}
};
Thank you.
You can set a property on the post:
$scope.downvote = function(post) {
posts.downvote(post);
post.hadDownvote = true;
};
Then check the property in an ng-style attribute:
<span ng-style="post.hadDownvote ? {color:'red'} : {}" class="glyphicon glyphicon-thumbs-down" ng-click="downvote(post)"></span>
Naturally, for release you may prefer to use a CSS class defined elsewhere and perform the same check with ng-class to add the class.
you have to drive it via binding so in ur controller do this but make sure u assing default isDownVote to true or false
$scope.downvote = function(post) {
posts.downvote(post);
post.isDownVoted = !post.isDownVoted;
};
then in ur html do this
<span class="glyphicon glyphicon-thumbs-down" ng-click="downvote(post)" ng-class="post.isDownVoted===true ? 'some-color' : ''" ></span>
some-color is ur class where you can put ur css.

How to change text in this case using ng-if or other expression?

I'm trying to change the text in a title tag based on a tag's direction value:
<li ng-repeat="t in tags">
<div class="tag"
ng-class="{'green-up': t.direction == 'positive',
'red-down': t.direction == 'negative',
'' : t.direction == 'stagnant'}"
title="Percentage increase"
ng-if="">{{t.name}}</div>
</li>
The direction is either positive, negative or stagnant, which should correspond to title="Percentage increase" title="Percentage decrease" or just title="Percentage"
What Angular syntax would be best used in this case?
Why not set up the tag settings as an object
$scope.tagInfo = {
positive:{ class:"green-up", title:"Percentage increase" },
negative:{ class:"red-down", title:"Percentage decrease" }
}
and then call that in your ng-repeat
<div class="tag"
ng-class="tagInfo[t.direction].class"
title="{{tagInfo[t.direction].title}}">{{t.name}}</div>
http://jsfiddle.net/rLrh0Lr1/
If you absolutely positively must use a conditional clause rather than a mapping lookup, call a method like f.e title="{{getTitle(t.direction)}}
$scope.getTitle = function(direction) {
if (direction==="positive") {
return "Increase";
} else if (direction==="negative") {
return "Decrease";
}
};
http://jsfiddle.net/p6aysky5/
I don't really see the point at all of doing that though. All it contributes is making your code messier.

Dynamic ng-class value

I've got a directive with this markup:
<button type="button" ng-class="{ 'btn-disabled': button.isDisabled }">
As you can see, btn-disabled is added as a CSS class if the scope's button.isDisabled is truthy.
Also on the scope is a property button.glyphicon. If glyphicon is truthy, I'd like to add the value of it to the <button>'s class as well.
How can I do this?
Maybe not the nicest syntax, but you could use:
data-ng-class="[button.isDisabled ? 'btn-disabled' : '', button.glyphicon]"
You could add a function to ng-class.
<button type="button" ng-class="getClass()">...
and on the controller
$scope.getClass = function(){
return ($scope.button.isDisabled ? "btn-disabled " : " ") + ($scope.button.glyphicon || "");
}
By adding this as a function you could reduce one extra watch that will be created while doing it inline in the template and abstract the logic out of html.

Angularjs if-then-else construction in expression

Can I somehow use if-then-else construction (ternary-operator) in angularjs expression, for example I have function $scope.isExists(item) that has to return bool value.
I want something like this,
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div>{{isExists(item) ? 'available' : 'oh no, you don't have it'}}</div>
</div>
I know that I can use function that returns string, I'm interesting in possibility of using if-then-else construction into expression.
Thanks.
Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:
condition && (answer if true) || (answer if false)
So in example, something like this would work:
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>
UPDATE: Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
You can use ternary operator since version 1.1.5 and above like demonstrated in this little plunker (example in 1.1.5):
For history reasons (maybe plnkr.co get down for some reason in the future) here is the main code of my example:
{{true?true:false}}
You can easily use ng-show such as :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-show="isExists(item)">available</div>
<div ng-show="!isExists(item)">oh no, you don't have it</div>
</div>
For more complex tests, you can use ng-switch statements :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-switch on="isExists(item)">
<span ng-switch-when="true">Available</span>
<span ng-switch-default>oh no, you don't have it</span>
</div>
</div>
This can be done in one line.
{{corretor.isAdministrador && 'YES' || 'NÂO'}}
Usage in a td tag:
<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>
I am trying to check if a key exist in an array in angular way and landed here on this question. In my Angularjs 1.4 ternary operator worked like below
{{ CONDITION ? TRUE : FALSE }}
hence for the array key exist i did a simple JS check
Solution 1 : {{ array['key'] !== undefined ? array['key'] : 'n/a' }}
Solution 2 : {{ "key" in array ? array['key'] : 'n/a' }}

Categories