"ng-switch on" and "ng-switch" difference - angularjs

I was studiously reading the AngularJS API reference for the ngSwitch directive when I came to that part :
place an expression on the on="..." attribute (or the ng-switch="..."
attribute)
So of course I was wondering why there are two ways to place the expression since both of them seems to work the same way.
<div ng-switch="expression">
<div ng-switch on="expression">
I assume there is a reason but I do not find anything for now.
Plunker to test : http://plnkr.co/edit/VAq1t4744bnNC6RgZtEn?p=preview

There is no difference.
You can check the sources of ng-switch directive
https://github.com/angular/angular.js/blob/master/src/ng/directive/ngSwitch.js
var watchExpr = attr.ngSwitch || attr.on

Related

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

when should I write code with `{{}}` and without `{{}}` in html of angular js project

May be This is a simple question but it is challenging for me.
In angularJS when i write {{}} in html code so i write code like this like
if i talk about dynamic id, we write like code this
<div ng-repeat = 'item in itmes track by $index'>
<div id = "div-{{$index}}">{{item.name}}</div>
</div>
If i use any model without {{}} i write this example
<input id = 'name' ng-model = "item.name"/>
whenever i am coding in angular js, i write code without {{}} then if it is not work then i try code with {{}} and vise versa. and randomly 1 will correct
Question is when i write code with {{}} and without {{}} in html code ?
After the OP explained what exactly was the problem.
So, the question here is very simple: when do we use {{}} and when we don't in the context of ng-model.
When you do a <input type=... ng-model="someModel>, what you're essentially telling Angular is: "Here is an input element; attach $scope's someModel variable to the value of this input element.
Now, you can use this in your JavaScript controller like so: $scope.someModel, but what about HTML? We have a templating language in Angular, and when you give it some variable (say someModel), it'll search its $scope for it, and then put in the value there. If it is unable to, it'll throw a nasty error.
In essence, {{}} GETS the value, without that, you generally set the variable to gold the value of something.
Very simply put, AngularJS thinks that the content within the brace is an expression, which must be resolved. Once it is, Angular puts the value of the resolved expression there. In the most basic of the terms, you just tell it: "Here is some expression; put the evaluated value instead."
In ES6, we call it template strings.
So, you'll use it for expressions which mutate after every iteration. Say, a loop or something. Places where you know what the answer is, or you have static content, you won't use it.
Say you have the following bit of code:
...
...
$scope.figureOne = 10;
in your controller.js and the following in its view file:
<div>My age is {{ figureOne }}</div>
Angular gets the value from the $scope, and puts it there; so, the rendered form will be: My age is 10. However, if you had the following
<div>My age is figureOne</div>
This time, Angular knows that there is nothing to evaluate or resolve, so, it'll just render it as it is: My age is figureOne.
I hope I made it clear! :)
Angular directives have different types of parameters. Some parameters (#) expect string values and some expect javascript expressions (=) (with variables bound to $scope).
There's no obvious way to know which parameter expects what type of value (aside from looking at documentation).
If a variable expects static string value and you have an angular expression
then you'll need to evaluate it by wrapping in {{}}
If there variable expects an expression and you have an expression
simply type that in.
It's the best to avoid using {{}} where possible, your dynamic ID will fail when Angular hasn't interpolated the expression yet, use ng-attr-id="div-{{$index}} for that. https://docs.angularjs.org/guide/directive#-ngattr-attribute-bindings
Another example, if you have a slow connection and Angular isn't loaded yet users will see the {{}}, you can avoid this by using ng-bind="".
See this thread for more info: AngularJS : Why ng-bind is better than {{}} in angular?
It is very simple.
{{something}} - used for one way binding(Static).
<input type="text" value="{{something}}">
Now if you change its value in HTML ,you can not get it by $scope.something in js.
but If you use ng-model="something",you can get its value in JS.
This happens because ng-model is two way binding.
<input type="text" ng-model="something">
Mostly We use ng-model for forms and {{}} to display static information like User details or else.

Conditional ng-include together with ng-controller in AngularJS

I have a conditional ng-include directive with a ng-controller associated, but it seems the controller isn't run when the condition is true.
The target is to include the template only when the condition is met and avoid the TypeError: Cannot call method 'insertBefore' of null issue.
For example:
<div ng-include src="myContent.imgList ? 'ui/image-list.html' : null" ng-controller="ImgListSubCtrl">
</div>
When myContent.imgList is filled with data, I expect the image-list.html template to be appended to the DOM and ImgListSubCtrl to be run, but it isn't.
Is this the expected behavior?. I'm using Ionic Framework with Angular 1.2.17.
Thank you.
I already found an explanation, though further comments are welcome.
The following Codepen shows the mentioned behavior and the solution (in Ionic Framework 1.0.0-beta12): http://codepen.io/anon/pen/FnojD?editors=101
The first include doesn't display any count, though the second one displays it correctly.
It seems that when using ng-include along with ng-controller, the controller is only run once, even when the ng-include src expression evaluates to null.
To run it when the template is actually included (when ng-include src isn't null), a solution is to avoid the conditional ng-include and wrap it in a ng-if block, so the whole element is re-created dynamically, as shown in the Codepen above.
In the example from the question:
<div ng-if="myContent.imgList">
<div ng-include src="'ui/image-list.html'" ng-controller="ImgListSubCtrl">
</div>
</div>
I hope it helps.

Angular interpolation expression not evaluated

I am having an issue with Angular interpolation.
I have a directive template that looks like this:
<div class="autocomplete {{attrs.class}}" id="{{attrs.id}}">
<input type="text" {{attrs.autofocus | toAutofocusText}} ng-model="searchParam" placeholder="{{attrs.placeholder}}"/>
...
</div>
The problem I have is that this expression is not evaluated:
{{attrs.autofocus | toAutofocusText}}
However, if I change this to something like this:
x="{{attrs.autofocus | toAutofocusText}}"
It does get evaluated.
Could someone explain me why this would be happening? I am guessing it is something fairly fundamental, but I can't find anything on Google.
So the answer is that attributes don't get interpolated on that level. Or to be more specific, at the time when your HTML is compiled, angular processes DomElements. A Dom element with an attribute that starts with {{ isn't a valid attribute, which is why the $compile don't know about it. However, it does now about such expressions within attribute values, or Dom element contents.
Remember that angular is (they say) what html would be if written for applications. The data binding syntax is evaluated as html. Saying:
x="{{attrs.autofocus | toAutofocusText}}"
is different because now you are talking about an attribute's property being evaluated not some unknown characters inside an html element.
Another thing I would recommend is you look into using ng-class for manipulating the class stuff:
http://docs.angularjs.org/api/ng/directive/ngClass

Include behaviour inside ng-switch

I'm building a reasonably non-trivial Angular-js application for the first time and am trying to establish some intuition about how to get things done. Most things are making sense, but there's one pattern in particular that has me stumped -
Whenever I place an "include" style directive inside an ng-switch, it is ignored. I've experimented with just about every style of ng-switch, ng-include, and ng-transclude I can think of to achieve the desired behaviour, but to no avail. I haven't noticed any documentation indicating that this would be disallowed, nor any equivalent style of pattern.
Here is an example of what I have tried to do:
<div ng-switch="is_logged_in()">
<div ng-switch-when="true">
logged-in:
<div ng-include="'views/logout.html'"> </div>
</div>
<div ng-switch-default>
not-logged-in
</div>
</div>
The expected behaviour being that the logout form is displayed when $scope.is_logged_in() returns true.
The behaviour I see is that "logged-in:" is displayed, but the include isn't.
I've tried various versions of Angular-js. I've inspected the network traffic and seen that the include is in-fact being fetched, but I can't get this to work. I've had the same behaviour manifest when trying to build my own template control structures using directives.
The way I've seen most examples dodge this is by using JS in a directive to manually show/hide various sections of the transcluded content - is this really the idiomatic way to get the behaviour I'm looking for?
Thanks!
While using ng-include I always assign the path to a variable in controller.
$scope.logoutlink ='views/logout.html'
And in the view you can assign as
<div ng-include="{{logoutlink}}"> </div>
It would be helpful to post a JSfiddle link.

Resources