Is it possible to evaluate an angular expression in a ng-if?
For instance:
<div ng-if="itemData.contentTypeId = {{$root.res('resources', article_type_id')}}">
<!-- some content -->
<div>
also tried surrounding the expression in single quotes:
<div ng-if="itemData.contentTypeId = '{{$root.res('resources', article_type_id')}}'">
<!-- some content -->
<div>
and neither worked as expected.
Is this an issue with syntax or is this not possible? If this is a syntax issue, how should the statement above be written?
The ng-if text IS an angular expression. Whatever string you write in there gets parsed by angular using $scope.$eval(). Any variables (including functions) that are used in the expression must be visible from the current $scope.
That means for this code to work, $scope.$root must be defined. Make sure it is, or you can't run the res() function, or else find another way.
ng-if evaluates the expression to a truthy or falsey value, so your = must be a comparison operator == or ===.
<div ng-if="itemData.contentTypeId === $root.res('resources', article_type_id')">
Related
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).
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
I am following the phonecat Angular tutorial here and I was wondering what this code was doing:
<div class="phone-images">
<img ng-src="{{img}}"
class="phone"
ng-repeat="img in phone.images"
ng-class="{active:mainImageUrl==img}">
</div>
Is {active:true} an angular construct? If so, what does it do and where is the documentation? Why the single {}?
Will {{img}} work in ng-src even though it's above the ng-repeat line?
ng-class is a directive, that expects an Angular expression. The type of the expression can be a string (the name of the class), an array of strings (the names of the classes), or an object where keys are the names of the classes, and values are booleans telling if the class must be added or not.
In that case, the expression is a literal JavaScript object, just as you would write it in JavaScript code:
var object = {active: mainImageUrl == img};
And the CSS class 'active' will thus be added if mainImageUrl == img is true.
Please note Double {{ }} :
http://docs.angularjs.org/api/ng.directive:ngMouseleave
Please note single Single: { }
http://docs.angularjs.org/api/ng.directive:select
Does it have something to do with "in the quotes" or "in the tag?" Please confirm. And does any one know why?
Of course the vast level of info on the handlebars site does not help:
The double braces are for one-way binding a model to the template, essentially stick the value of the model into that location.
The single braces signify what type of value the attribute expects. For example:
<select
ng-model="{string}"
[name="{string}"]
[required]
[ng-required="{string}"]
[ng-options="{comprehension_expression}"]>
</select>
ng-model expects a string
name (optional) expects a string
required (optional) expects no value
ng-required (optional) expects a string
ng-options (optional) expects an Angular comprehension expression
The string values can be Angular expressions
Versus this, which is just a direct binding:
<body>
<button ng-mouseleave="count = count + 1" ng-init="count=0">
Increment (when mouse leaves)
</button>
count: {{count}}
</body>
Where the value count on the scope replaces {{count}}
Both ways you provide a expression which are like javascript expressions.
HTML attributes that have been extended by angularjs and take an expression can take any expression without using interpolation symbol {{}}. Single {} is just to signify what should be provided.
Everywhere else you use interpolation {{}}
See documentation on expressions here http://docs.angularjs.org/guide/expression
I've tried to read the documentation on ng-include with no luck thus far. All I want to do is have the ng-include evaluate the path of where the template/partial is and load the contents:
<div data-ng-include src="'{{pageData.src}}'"></div>
I can see pageData.src is returning "tpl/page.html" in the console. I've tried the following variations:
<div data-ng-include src="{{pageData.src}}"></div>
<div data-ng-include src='{{pageData.src}}'></div>
<div data-ng-include src={{pageData.src}}></div>
None of them seem to evaluate the expression. I receive the following error:
Error: [$parse:syntax] http://errors.angularjs.org/1.2.9/$parse/syntax?p0=pageData.src&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=3&p3=%7B%7BpageData.src%7D%7D&p4=pageData.src%7D%7D
Feedback is much appreciated!
In ng-include src takes a javascript expression so in your case the following should work:
<div data-ng-include src="pageData.src"></div>
when you see it like this
<div data-ng-include src="'templates/myTemplate.html'"></div>
the extra single quote inside the double quotes is a javascript expression in this example a string literal.
when you see {{}} this is for directives that do not take javascript expressions but just a string. For example ng-href takes a string. That string can be the result of a js expression which should be enclosed on {{}} e.g.
<a ng-href="{{pageData.src}}/myImage.jpg">Go</a>
Finally to mention something that confused me which was when there is an expression with single curlies {}. e.g.
<a ng-class="{'active': item.active, 'locked': item.disabled}">Go</a>
in this case this is a js map expression and the ng-class takes the name that has a value the evaluates to true. So if in the above item.active evaluates to true then 'active' will be added as a class.
Try this:-
<div data-ng-include="pageData.src"></div>
If you can post a jsFiddle, it would be easy for me to see the exact problem.