ng-class doesnot get evaluated - angularjs

<div ng-if="question.type =='options'" ng-repeat="option in question.options" >
<ion-radio name="{{$parent.question.id}}"
ng-model="$parent.question.answer"
required ng-value="option.id"
ng-class="{'has-custom-error':submitted && questionForm.{{$parent.question.id}}.$invalid,
'has-custom-success':questionForm.{{$parent.question.id}}.$valid }"
>
{{option.text}}
</ion-radio>
</div>
I have to add has-custom-error on user submitting the form without selecting the option.That is form is not valid but the ng-classis not getting evaluated.
The demo code is over here:http://plnkr.co/edit/FwjoCTYONvi3BoFHNKFK?p=preview

I don't think it is possible to use {{ }} expressions on a ng-class expression. You should be able to use it like this questionForm[$parent.question.id]
Also I never got ng-class working with classes with - between the parts, only CamelCase like hasCustomError. So {hasCustomError: questionForm.$invalid} should work.
Have you considered using the styleClass ng-invalid-required that is already used by angular for your styling? It is usually a lot cleaner, since there is no need for all the ng-class expressions

There is at least one problem with your code. You must not use interpolation {{}} within your ng-class attribute. Here is the correct syntax:
ng-class="{'has-custom-error':submitted && questionForm[$parent.question.id].$invalid, 'has-custom-success':questionForm[$parent.question.id].$valid }"

When you are inside an Angular expression, you don't need the mustache braces. So your code should be:
<div ng-if="question.type =='options'" ng-repeat="option in question.options">
<ion-radio name="{{$parent.question.id}}"
ng-model="$parent.question.answer"
required ng-value="option.id"
ng-class="{'has-custom-error':submitted && questionForm[$parent.question.id].$invalid,
'has-custom-success':questionForm[$parent.question.id].$valid }">
{{option.text}}
</ion-radio>
</div>
The variable form a.b has been replaced by the indexer form a["b"] so that it is evaluated correctly.

You can't use double-mustached expressions ({{ ... }}) inside expressions. The ng-class value is already an expression of type object, so you're supposed to use JavaScript syntax inside this attribute:
ng-class="{'has-custom-error': submitted && questionForm[$parent.question.id].$invalid,
'has-custom-success': questionForm[$parent.question.id].$valid }"
The use of $parent is also unecessary. BTW, you're not using it for your ng-repeat expression:
ng-repeat="option in question.options"
So you should simply use question instead of $parent.question: the scope of the ng-repeat block inherits from its parent scope, and the question is thus available through inheritance.
Note that, playing with your plunkr, it seems like the ion-radio directive that you're using doesn't correctly set the name attribute of the input it generates. This is probably why the CSS classes don't appear.

ng-form is the solution to my problem.But the problem that I am facing is in the name attribute of my ion-radio directive. For radio hence i used angular ng-invalid-required.And for other html tag i used ng-form.$invalid

Related

Angular - add class to button if on page [duplicate]

Is there any way to make an expression for something like ng-class to be a conditional?
For example, I have tried the following:
<span ng-class="{test: 'obj.value1 == \'someothervalue\''}">test</span>
The issue with this code is that no matter what obj.value1 is, the class test is always applied to the element. Doing this:
<span ng-class="{test: obj.value2}">test</span>
As long as obj.value2 does not equal a truthy value, the class in not applied. Now I can work around the issue in the first example by doing this:
<span ng-class="{test: checkValue1()}">test</span>
Where the checkValue1 function looks like this:
$scope.checkValue1 = function() {
return $scope.obj.value === 'somevalue';
}
I am just wondering if this is how ng-class is supposed to work. I am also building a custom directive where I would like to do something similar to this. However, I can't find a way to watch an expression (and maybe that is impossible and the reason why it works like this).
Here is a plnkr to show what I mean.
Your first attempt was almost right, It should work without the quotes.
{test: obj.value1 == 'someothervalue'}
Here is a plnkr.
The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here.
If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.
Just to complement: You can also use logical operators to form logical expressions like
ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"
Using ng-class inside ng-repeat
<table>
<tbody>
<tr ng-repeat="task in todos"
ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',
'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">
<td>{{$index + 1}}</td>
<td>{{task.name}}</td>
<td>{{task.date|date:'yyyy-MM-dd'}}</td>
<td>{{task.status}}</td>
</tr>
</tbody>
</table>
For each status in task.status a different class is used for the row.
Angular JS provide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.
Type 1
<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>
In this code class will be apply according to value of status value
if status value is 0 then apply class one
if status value is 1 then apply class two
if status value is 2 then apply class three
Type 2
<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>
In which class will be apply by value of status
if status value is 1 or true then it will add class test_yes
if status value is 0 or false then it will add class test_no
I see great examples above but they all start with curly brackets (json map). Another option is to return a result based on computation. The result can also be a list of css class names (not just map). Example:
ng-class="(status=='active') ? 'enabled' : 'disabled'"
or
ng-class="(status=='active') ? ['enabled'] : ['disabled', 'alik']"
Explanation: If the status is active, the class enabled will be used. Otherwise, the class disabled will be used.
The list [] is used for using multiple classes (not just one).
There is a simple method which you could use with html class attribute and shorthand if/else. No need to make it so complex. Just use following method.
<div class="{{expression == true ? 'class_if_expression_true' : 'class_if_expression_false' }}">Your Content</div>
I am going to show you two methods by which you can dynamically apply ng-class
Step-1
By using ternary operator
<div ng-class="condition?'class1':'class2'"></div>
Output
If your condition is true then class1 will be applied to your element else class2 will be applied.
Disadvantage
When you will try to change the conditional value at run time the class somehow will not changed. So I will suggest you to go for step2 if you have requirement like dynamic class change.
Step-2
<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>
Output
if your condition matches with value1 then class1 will be applied to your element, if matches with value2 then class2 will be applied and so on. And dynamic class change will work fine with it.
Hope this will help you.
Angular syntax is to use the : operator to perform the equivalent of an if modifier
<div ng-class="{ 'clearfix' : (row % 2) == 0 }">
Add clearfix class to even rows. Nonetheless, expression could be anything we can have in normal if condition and it should evaluate to either true or false.
Using function with ng-class is a good option when someone has to run complex logic to decide the appropriate CSS class.
http://jsfiddle.net/ms403Ly8/2/
HTML:
<div ng-app>
<div ng-controller="testCtrl">
<div ng-class="getCSSClass()">Testing ng-class using function</div>
</div>
</div>
CSS:
.testclass { Background: lightBlue}
JavaScript:
function testCtrl($scope) {
$scope.getCSSClass = function() {
return "testclass ";
}
}
For Angular 2, use this
<div [ngClass]="{'active': dashboardComponent.selected_menu == 'mapview'}">Content</div>
use this
<div ng-class="{states}[condition]"></div>
for example if the condition is [2 == 2], states are {true: '...', false: '...'}
<div ng-class="{true: 'ClassA', false: 'ClassB'}[condition]"></div>
ng-class is a Directive of core AngularJs. In which you can use "String Syntax", "Array Syntax", "Evaluated Expression", " Ternary Operator" and many more options described below:
ngClass Using String Syntax
This is the simplest way to use ngClass. You can just add an Angular variable to
ng-class and that is the class that will be used for that element.
<!-- whatever is typed into this input will be used as the class for the div below -->
<input type="text" ng-model="textType">
<!-- the class will be whatever is typed into the input box above -->
<div ng-class="textType">Look! I'm Words!
Demo Example of ngClass Using String Syntax
ngClass Using Array Syntax
This is similar to the string syntax method except you are able to apply multiple classes.
<!-- both input boxes below will be classes for the div -->
<input type="text" ng-model="styleOne">
<input type="text" ng-model="styleTwo">
<!-- this div will take on both classes from above -->
<div ng-class="[styleOne, styleTwo]">Look! I'm Words!
ngClass Using Evaluated Expression
A more advanced method of using ngClass (and one that you will probably use the most) is to evaluate an expression. The way this works is that if a variable or expression evaluates to true, you can apply a certain class. If not, then the class won't be applied.
<!-- input box to toggle a variable to true or false -->
<input type="checkbox" ng-model="awesome"> Are You Awesome?
<input type="checkbox" ng-model="giant"> Are You a Giant?
<!-- add the class 'text-success' if the variable 'awesome' is true -->
<div ng-class="{ 'text-success': awesome, 'text-large': giant }">
Example of ngClass Using Evaluated Expression
ngClass Using Value
This is similar to the evaluated expression method except you just able to compares multiple values with the only variable.
<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>
ngClass Using the Ternary Operator
The ternary operator allows us to use shorthand to specify two different classes, one if an expression is true and one for false. Here is the basic syntax for the ternary operator:
ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">
Evaluating First, Last or Specific Number
If you are using the ngRepeat directive and you want to apply classes to the first, last, or a specific number in the list, you can use special properties of ngRepeat. These include $first, $last, $even, $odd, and a few others. Here's an example of how to use these.
<!-- add a class to the first item -->
<ul>
<li ng-class="{ 'text-success': $first }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
<!-- add a class to the last item -->
<ul>
<li ng-class="{ 'text-danger': $last }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
<!-- add a class to the even items and a different class to the odd items -->
<ul>
<li ng-class="{ 'text-info': $even, 'text-danger': $odd }" ng-repeat="item in items">{{ item.name }}</li>
</ul>

What is the diff between using {{...}} and without {{...}} and angular directives?

Actually I'm confused between when to use {{ }} when using angular directives and when to not to use {{ }}
For example:
<div data-ng-init="isHidden=false">
<div data-ng-show="isHidden">
...
</div>
</div>
and
<div data-ng-init="isHidden=false">
<div data-ng-show="{{isHidden}}">
...
</div>
</div>
I'm confused between these syntax ? What are the differences between those? And when to use what? Thanks in advance :)
There is no difference except the "look" u need to use the {{value}} syntax in case you want to write data anywhere in your html body
<div>{{value}}</div>
It's all explained here: Difference between double and single curly brace in angular JS?
For quick answer:
{{}} are Angular expressions and come quite handy when you wish to
write stuff to HTML
Don't use these at a place that is already an expression!
For instance, the directive ngClick treats anything written in between
the quotes as an expression
<div data-ng-init="isHidden=false">
<div data-ng-show="isHidden">
...
</div>
</div>
In This Situation data-ng-show = false , Takes From data-ng-init As Statically,if You Have Given true Then It Returns True .
But Here
<div data-ng-init="isHidden=false">
<div data-ng-show="{{isHidden}}">
...
</div>
{{}} Called As Expressions In Angular One Of The Most Important Concept
It Directly Evaluate If isHidden = true Or False Based On Any Condition Written In Your App.js File .
Example:
<div data-ng-init="isHidden=YourVariable">
<div data-ng-show="{{isHidden}}">
...
</div>
if(YourVariable == true){
Do Somthing
}
else{
Do Something
}
If you are asking when to use {{}} while assigning value to a attribute and when not.
It depends on the binding types of directive. '#' or '='
So here, you have to use:
data-ng-show="{{isHidden}}" if the binding type of directive scope data-ng-show is '#', that mean the data-ng-show will be expecting a string value. So in this case if you keep data-ng-show="isHidden" it will take data-ng-show's value as 'isHidden', but data-ng-show="{{isHidden}}" will take the value of the $scope.isHidden and assign to data-ng-show.
Now if the binding type of directive scope data-ng-show is '=', that means the data-ng-show will be expecting a value from a scope. So data-ng-show="isHidden" itself will take the value of he $scope.isHidden and assign to data-ng-show.
Note: all the default HTML attributes expect a string so you have to use {{}} for default HTML attributes.
There is no as such major difference unless one uses them in the DOM for the value.
When one uses the following:
<div data-ng-show="isHidden">
then, expression is evaluated and on the basis of it respective value, the ng-show either hides or displays the div. But the value of the isHidden cannot be seen, when one inspects the HTML using the browser developer tool.
When one uses the following:
<div data-ng-show="{{isHidden}}">
In this case, the value of the isHidden can be seen from the developer tools, and the rest of the expression does evaluates the same as that of (1).

When to use double braces {{}} in angularJS

Taken from the Angular documentation:
Angular Expressions
Angular expressions are JavaScript-like code snippets that are mainly
placed in interpolation bindings such as
<span title="{{ attrBinding }}">{{ textBinding }}</span>
but also used directly in directive
attributes such as ng-click="functionExpression()".
For example, these are valid expressions in Angular:
1+2 a+b user.name items[index]
However I'm a little confused as to when to use the double braces syntax {{}} and when not to. The documentation seems to suggest that you don't need them when using expressions within the directive attributes (see the ng-click example above).
Although the following code which works offers anecdotal evidence to the contrary:
<ul id="Menu">
<li ng-repeat="appModule in applicationModules"
id="{{appModule.Name}}"
ng-class="{ 'selected' : selectedAppModule == '{{appModule.Name}}' }"
ng-click="menuClicked(appModule.Name)">
{{appModule.Display}}
</li>
</ul>
Note how in the ng-class directive the double braces are used and inside the ng-click directive they are not.
How do you know when to use them and when not to?
It depends on the directive attribute in question and the type of binding it uses. Further more it depends on what you intend in the given situation.
From your example:
ng-repeat="appModule in applicationModules"
No need for the braces as this expression is evaluated by angular inside the ng-repeat directive.
id="{{appModule.Name}}"
Here we need braces as we want the id to be equal to the value of the expression.
ng-class="{ 'selected' : selectedAppModule == '{{appModule.Name}}' }"
I'm pretty sure this can be written as:
ng-class="{ 'selected' : selectedAppModule == appModule.Name }"
And you get the same behaviour.
ng-click="menuClicked(appModule.Name)"
In this example we need the ng-click to be bound to the method named menuClicked.
Generally we use {{}} when we want to evaluate the expression and when dealing with attributes we don't always need to use {{}} as they are in many cases evaluated behind the scenes.
Simple Tip A rule of thumb for when {{}} is needed is by thinking of it as a wrapper for a .ToString()-method. Does converting the expression to a string make sense, then so does using {{}}. (Any counter examples are very welcome)
Check the documentation. Avoid using using interpolation {{ }} when
the documentation says that the directive takes an expression, . In the case of ng-src, the documentaion explicitly says use {{ }}. If the attribute is not an AngularJS directive, use interpolation.
Erroneous
ng-class="{ 'selected' : selectedAppModule == '{{appModule.Name}}' }"
The above example is an example of mixing interpolation and Angular epressions.
Instead use:
ng-class="{ 'selected' : selectedAppModule == appModule.Name }"
From the Docs:
Why mixing interpolation and expressions is bad practice:
It increases the complexity of the markup
There is no guarantee that it works for every directive, because interpolation itself is a directive. If another directive accesses attribute data before interpolation has run, it will get the raw interpolation markup and not data.
It impacts performance, as interpolation adds another watcher to the scope.
Since this is not recommended usage, we do not test for this, and changes to AngularJS core may break your code.
— AngularJS Developer Guide - mixing interpolation and expressions
Update
Don't use interpolation with:
ng-selected, see AngularJS ng-selected Directive API Reference
ng-disabled, see AngularJS ng-disabled Directive API Reference
ng-required
ng-if
ng-show
ng-hide
ng-open
ng-value
ng-repeat
ng-options

How do I display an Angular directive conditionally?

I'm attempting to use Angular directives to create custom input field types. For example, I have a type called "duration" which draws three separate hours, minutes, and seconds fields. I'm trying to use the directive as an attribute of an input element, and the directive replaces the input element.
For example, in the following code:
<input duration>
Would be rendered as a <div> with several inputs inside of it, and the original input would be out of the picture.
I'm running an ngRepeat loop through several form fields of different types, including duration. I'd like to find a way that only requires me to put one input in the HTML, with the duration attribute applied only if the field is supposed to be of duration type. I tried the following:
<div ng-repeat="field in fields">
<input type='{{field}}' ng-attr-duration="field==='duration'">
</div>
The problem with that code is that every element is rendered as duration because ng-attr-duration gets evaluated to duration='false' when the field is not duration, which triggers my directive.
Is there a way for me to apply the directive conditionally without having to define multiple <input>s to reduce redundancy in my code?
Take a look at what the directive docs say about ng-attr:
When using ngAttr, the allOrNothing flag of $interpolate is used, so if any expression in the interpolated string results in undefined, the attribute is removed and not added to the element.
Note that you need to be using curly braces so Angular will interpolate the expression. And, if your expression has an undefined term in it, the attribute won't be added.
How about something like this:
<div ng-repeat="field in fields">
<input type='{{field}}' ng-attr-duration="{{field==='duration' ? true : undefined}}">
</div>
The true in the ternary expression can be whatever you want, just not undefined.
What i can think of you can use condition if-else of ng-switch
<div ng-repeat="field in fields">
<div ng-switch on="field">
<input ng-switch-when="true" type='{{field}}' ng-attr-duration="field==='duration'">
<input ng-switch-default="true" type='{{field}}'>
</div>
</div>
It will also maintain readability of code.

ng-show and ng-model can't work together on the same $scope variable

I am trying to have a span element show some $scope variable only if it is not null or empty.
I know i can accomplish this with only ng-model, but i don't understand they this won't work:
<span ng-show="x !== null" ng-model="x"></span>
or something similar to this.
ng-model is for two-way binding (as #MK Safi said above), which means its for elements that both display values and allow users to change those values. Probably not a <span/>...
If you're just looking to show the value of the model in the span, use ng-bind or expression syntax - {{ x }}
This way, ng-show should work properly to add the relevant CSS styles as x changes.
E.g.:
<span ng-bind="x" ng-show="x !== null"></span>
or
<span ng-show="x !== null">{{ x }}</span>
ng-model is used mostly for input, textarea, and select elements. It's not used on span, div, or p elements, etc.
From Angular documentation on ngModel
The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
Yes, as MK Safi says ng-model is only used to bind inupts to $scope variables. This should work though:
<span ng-show="x !== null">{{ x }}</span>
Just use the templating engine to display the value in $scope.x

Resources