AngularJS Expressions

AngularJS binds data to HTML using expressions. These expressions are JavaScript-like code snippets that are placed in what are known as interpolation bindings. The syntax for every AngularJS expression is as follows: {{ expression }}. These bindings can be placed directly in between the opening and closing tags of an element, or assigned to an attribute inside the actual element within two sets of curly braces: {{ textBinding }}. These expressions can also be written inside a directive: ng-bind="expression". Using curly braces indicates an AngularJS expression and behaves the same way as the ngBind directive. AngularJS returns the result exactly where the expression was written after the expression is resolved. Valid expressions can contain literals, operators, and variables:

1 + 2
a + b
user.name
Items[index]

Here is a brief example of an AngularJS expression that also demonstrates how numbers in AngularJS work in the same fashion as numbers do in regular JavaScript:

See the Pen [AngularJS Expressions] Example by Dash (@binarynectar) on CodePen.

Moreover, you can use number in Angular expressions dynamically by using directives:

See the Pen [AngularJS Expressions] Filters by Dash (@binarynectar) on CodePen.


In the example above, we declare a variable using the ngModel directive. The variable’s value is later displayed in the expression. Note that we also have something called a filter where the result value of a given expression is transformed into a specific format. Here, the currency filter is used with predictable results. Filters are always specified after the pipe symbol (|).

AngularJS will resolve the expression, wherever it may be, and return the result. For example, AnguluarJS can change the value of CSS properties. The example below changes the color of the text box when the value inside the text box is changed:

See the Pen [AngularJS Expressions] CSS by Dash (@binarynectar) on CodePen.

The following example demonstrates how AngularJS strings and JavaScript strings are pretty much the same thing:

See the Pen [AngularJS Expressions] Strings by Dash (@binarynectar) on CodePen.

This example demonstrates how to use the ngBind directive with Angular expressions:

See the Pen [AngularJS Expressions] ngBind by Dash (@binarynectar) on CodePen.

There really isn’t much a difference between using the ngBind directive or the curly braces. However, you might actually see the curly braces for an instant before the expression is resolved. The ngBind directive prohibits this flicker behavior from ever occurring.

Angular treats objects in expressions just like JavaScript treats objects in regular JavaScript expressions:

See the Pen [AngularJS Expressions] Objects by Dash (@binarynectar) on CodePen.

This example of using the ngBind directive is a bit more complex than the first:

See the Pen [AngularJS Expressions] Another ngBind Example by Dash (@binarynectar) on CodePen.

Here is an example of an Angular expression involving an array:

See the Pen [AngularJS Expressions] Arrays by Dash (@binarynectar) on CodePen.

And here is the same example, except using the ngBind directive:

See the Pen [AngularJS Expressions] Array with ngBind by Dash (@binarynectar) on CodePen.

But, enough with the similarities. AngularJS expressions is not JavaScript. There are various differences between JavaScript expressions and AngularJS expressions. The first and foremost and probably obvious difference is that you can use AngularJS expressions in HTML, while with JavaScript expressions, you cannot. The second major difference between the two is the context. JavaScript expressions are evaluated against the global window object. Angular expressions are evaluated against the scope object. Another major difference is how forgiving Angular expressions are in terms of generating errors. Angular expressions do not generate errors and are forgiving to undefined and null values. JavaScript will generate a ReferenceError or TypeError when trying to evaluate undefined properties. Also, Angular expressions uses filters to format data before the data is displayed. JavaScript has no such construct.

Other constructs that AngularJS expressions do not allow are control flow statements, function declarations, regular expression creation, object creation with the new operator, bitwise operators, the comma operator, and the void operator.

Removing the ng-app directive, will cause the expression to display as it is without AngularJS solving it:

See the Pen [AngularJS Expressions] No NgApp by Dash (@binarynectar) on CodePen.

The following example is a little more complex as it evaluates an entered expression and lists the output:

See the Pen [AngularJS Expressions] Complex Example by Dash (@binarynectar) on CodePen.

AngularJS uses the $parse service to evaluate expressions rather than using the eval() function. Angular expressions do not have direct access to global variables such as window, document, and location. This intentional restriction prevents accidental access to globals, which can cause subtle bugs. Angular provides services such as $window and $location in case a developer needs to use an alternative to the window and location global variables. These services can be used in controller functions that can in turn be called from expressions. The following example demonstrates this:

See the Pen [AngularJS Expressions] Using Angular Services by Dash (@binarynectar) on CodePen.

In JavaScript, a.b.c will result in a thrown exception if a is not an object. With Angular expressions, the idea is to show nothing than throw an exception if a is undefined. There are valid cases when a may be undefined, such as waiting for the server to respond. If Angular expressions weren’t so forgiving, bindings would easily force developers to code like this: {{((a||{}).b||{}).c}}. Invoking a function a.b.c() on an undefined or null returns undefined, but does not raise an error.

You cannot write control flow statements in an Angular expression besides using the ternary operator: a ? b : c. The belief is that application logic should be in controllers and not views. Use a JavaScript method inside the expression if you deem it necessary to provide a conditional looping construct.

Another form of logic that is best placed in a controller are function declarations and regular expression creation. Functions and regular expressions cannot be created from within an AngularJS expression. Placing them in a controller makes them easier to test.

One-Time Binding

Introduced in Angular 1.3, a one-time expression is an expression that begins with “::” inside the curly braces. One-time expressions will stop recalculating once stable. If the expression result is a non-undefined value, stability occurs after the first digest. Here is an example:

See the Pen [AngularJS Expressions] One-Time Binding by Dash (@binarynectar) on CodePen.

There are some important benefits from using one-time binding. First off, one-time binding provides a way to create a binding that becomes deregistered and frees up resources once the binding has been stabilized. This reduces the number of expressions being watched, which in turn makes the digest loop faster and allows more information to be displayed and improves overall performance.

In other words, one-time binding expressions will retain the value at the end of the cycle as long as the value is not “undefined”. If the value of the expression is set to a value and then later set to “undefined” within the same digest loop, then the expression is not fulfilled and will remain watched. The actual algorithm is as follows:

1. When a digest loop is entered and a given expression that start with “::” is dirty-checked, store the value as V
2. Mark the result of the expression as stable if V is not undefined. Then schedule a task to deregister the watch for the expression when exiting the digest loop
3. Process the digest loop
4. When finished processing the digest loop and all values have been settled, process the queue of watch deregistration tasks. For every watch to be deregistered, check if the watch still evaluates to a value that is not “undefined”. If the watch evaluates to a value that is not “undefined”, deregister the watch. Otherwise, keep dirty-checking the watch in future digest loops by following the algorithm all over again starting from step #1.
An expression is an appropriate candidate for one-time binding if the expression does not change once set. For example, one-time binding for interpolating text or attributes may be a good idea:

text: {{::name | uppercase}}

Here is a complete list of every possible component of a valid AngularJS expression:

Integer

32

Floating point

3.2

Scientific notation

42E5
42e5
42e-5

Single-quoted string

'square'

Double-quoted string

"red"

Character escapes

"\n\f\r\t\v\'\"\\"

Unicode escapes

"\u2665"

Booleans

true
false

null

null

undefined

undefined

Arrays

[1, 2, 3]
[1, [2, 'three']]

Objects

{a: 1, b: 2}
{'a': 1, "b": 'two'}

A quick note on the ternary operator: ternary expressions are not supported in Angular expressions before version 1.1.5. However, they can be emulated: condition && (answer if true) || (answer if false)
EXAMPLE:


{{item.description}}
{{isExists(item) && 'available' || 'oh no, you don't have it'}}

https://docs.angularjs.org/guide/expression
Angular Expressions
http://www.w3schools.com/angular/angular_expressions.asp
AngularJS Expressions
https://teropa.info/images/angular_expressions_cheatsheet.pdf
AngularJS Expressions
https://www.tutorialspoint.com/angularjs/angularjs_expressions.htm
AngularJS – Expressions
http://www.encodedna.com/angularjs/tutorial/angularjs-expressions-with-examples.htm
AngularJS Expressions for Beginners – AngularJS Expressions Examples
http://blog.pathgather.com/blog/2014/12/7/learning-angularjs-magic-expressions
Learning AngularJS Magic: Expressions
http://stackoverflow.com/questions/16125872/angularjs-why-ng-bind-is-better-than-in-angular
AngularJS: Why ng-bind is better than {{}} in angular?
http://stackoverflow.com/questions/16584346/angularjs-if-then-else-construction-in-expression
Angularjs if-then-else construction in expression

The AngularJS Module

angular_coffee

The AngularJS framework supports a modular approach that helps keep logic separated and maintain effective code readability. In AngularJS, the module construct is a collection and container of services, directives, controllers, filters, and configuration information that define an AngluarJS application. These modular components support a separation of concerns known to the AngularJS framework. And by containing specific components in a module, AngularJS helps prevent the pollution of global scope. This post elaborates on some of the basics related to creating and utilizing an AngularJS module.

Continue reading

The ngApp Directive

angularjs_logo-svg
An AngularJS application is defined by the ngApp directive, which is found in the ng module of the AngularJS framework. This directive is used to easily auto-initialize an AngularJS application. The element from which the directive resides specifies the root element and the “owner” of the application.

Continue reading

JavaScript Callbacks

phone

JavaScript functions are known as first-class objects since they can be used like any other object: they can be stored in variables, passed as arguments, created within functions, and returned from functions. We can pass a function as an argument to another function and execute that passed-in function or even return it so that it can be executed later. These functions that are passed into another function as an argument are often referred to as callbacks.

Continue reading

The head Element

head
The HTML head element is essentially a container for general information about the document, otherwise known as metadata. Such data includes the title of the document and might include links to scripts, style sheets, RSS feeds, translations as well as JavaScript. Other kinds of information encapsulated by the head element may include the character set used within the page, a general description of the page content, and keywords to be used for search engines. Typically, the metadata is never actually seen by website visitors with the exception of the title element.

Continue reading

The html Element

Roots

Know your root element!

The html element represents the root element of an HTML document and is the container for all other HTML elements. It delimits an HTML document from beginning to end. All elements must be descendants of this element in a valid HTML document. It is the first tag in a document excluding comments and the <!DOCTYPE> tag. Remember that the <!DOCTYPE> tag is technically NOT an HTML tag.

Continue reading

git commit

wedding-rings-1379793

WARNING: If you are someone who is eagerly waiting for a proposal, I should warn you that this post has the word “commit” around 194 times. Tread carefully…

The git commit command, an important part of the regular Git workflow, saves a snapshot that includes any files with staged changes in the working directory. A snapshot is considered a “safe” version of the project. Git will never change a snapshot unless you explicitly ask Git to do so.

Continue reading

git add

Bella_Rose_Arts_Centre_StageThe git add command is part of the fundamental Git workflow and essentially adds or removes file content from the working directory to the staging area. Whether the changes belong to tracked files or not, the command signals to Git that you want to include changes for the next commit. The command itself doesn’t really affect the working directory since changes are not actually recorded until the git commit command is run.

Continue reading

How to Clone a Git Repository

2504312455_90c9df9d32_b

“Git those clones, Whiskers! Go git ’em!”

When you create a repository on a web-based Git repository hosting service like GitHub or BitBucket, you are creating a remote repository. With Git, you are able to clone the remote repository onto your own computer as a local copy and then synchronize between the two. This local copy is a full-fledged Git repository all on its own. It has a history, manages its own files, and it hosts a separate environment from the original repository.

Continue reading

1 2 3 4