Sunday, April 14, 2013

Exploring AngularJS expressions

This chapter will be a work in progress for the next few days.

So far we have learned the usage of directives and expressions in AngularJS. In previous chapters we saw that values of some directives can be expressions as well. The best part of expressions is that one can use them in HTML. So in a way it provides the power of JavaScript in HTML. In this chapter we will explore AngularJS expressions. The sub topics are:

if we can use JavaScript style syntax in AngularJS expressions

There are subtle differences between AngularJS expressions and JavaScript expressions. AngularJS has its own mechanism to parse the expressions and find the semantics out of it. In this section we will see which JS operators can be used in AngularJS expressions and which can't be. The following example shows the usage of various operators in AngularJS expressions. You can see output of the program by clicking on

use of "{{ }}" in value of HTML attributes or directives

{{ }} as you know is Angular's default delimiter for expression boundaries. It has to be used carefully in directives and HTML attributes and the reason is how AngularJS internally handles expressions. We will see that as well in coming chapters. For now let us focus on how to use expressions in HTML attributes in directives.

  • usage in HTML attributes: you should use {{ }} so that AngularJS can evaluate the expression.

  • for AngularJS directives(which can be attributes too): you should carefully use {{}} because it all depends on how the directive is written. Let me give you a few examples to illustrate my point. The explanation has been written in comments in the code.
    • Using {{}} in value of ng-switch

    • Using {{}} in value of ng-init

    • Using {{}} in value of ng-src

    So as you can see different directives process their attribute values differently. Some like ng-src expect you to use {{ }} in attribute values while some like ng-init do not. So as a rule of thumb you should always check the documentation of the directive for knowing if you can use {{ }} in its value.

Surely for some of you this chapter must have invoked curiosity about how AngularJS processes expressions and directives. In forthcoming chapters we will enjoy that too.

Found something incorrect?

Post a reply or mail us at   anirudhtomer at gmail dot com   or   toshish dot jawale at gmail dot com