Learn to use angularjs Templates to Create Views

angularjs templates provide a framework to represent the application view to the user. angularjs templates contain expressions, filters, and directives that define additional functionality and behavior to the DOM elements. The templates are built on top of normal HTML and extend the functionality of HTML by adding additional elements and attributes.

This article focuses on angularjs templates, as well as expressions and filters. Expressions enable you to implement JavaScript-like code alongside the HTML code in a template. Filters enable you to modify data values before you display them—for example, to format text.

Understanding Templates

angularjs templates are fairly straightforward yet very powerful and easy to extend. Templates are based on standard HTML documents but extend the HTML functionality with three additional components:

ImageExpressions: Expressions are bits of JavaScript-like code that are evaluated within the context of a scope. Expressions are denoted by {{}} brackets. The results of an expression are added to a compiled HTML web page. Expressions can be placed in normal HTML text or in the values of attributes, as shown here:

<p>{{1+2}}</p>
href="/myPage.html/{{hash}}"

ImageFilters: Filters transform the appearance of data that is placed on a web page. For example, a filter can convert a number from the scope into a currency string or a time string.

ImageDirectives: Directives are new HTML element names or attribute names within HTML elements. They add to and modify the behavior of HTML elements to provide data binding, event handling, and other support to an angularjs application.

The following code snippet shows an example of implementing directives, expressions, and filters. The ng-model="msg" attribute is a directive that binds the value of the <input> element to msg in the scope. The code in the {{}} brackets is an expression that applies the uppercase filter:

<div>
  <input ng-model="msg">
  {{msg | uppercase}}
</div>

When you load an angularjs web page into a browser, you load it in a raw state, containing template code along with HTML code. The initial DOM is built from that web page. When the angularjs application is bootstrapped, the angularjs template compiles into the DOM, dynamically adjusting the values, event bindings, and other properties of the DOM elements to the directives, expressions, and filters in the template.

Recommended :  Generate bar codes directly in your laravel app

During compilation, HTML tags and attributes are normalized to support the fact that angularjs is case sensitive, whereas HTML is not. Normalization does two things:

Image Strips the x- and data- prefixes from the front of elements and attributes.

Image Converts names with : or - or _ to camelCase.

For example, all of the following normalize to ngModel:

ng-model
data-ng-model
x-ng:model
ng_model

Using Expressions

Using expressions is the simplest way to represent data from the scope in an angularjs view. Expressions are encapsulated blocks of code inside brackets: {{expression}}. The angularjs compiler compiles an expression into HTML elements so that the results of the expression are displayed. For example, look at the following expressions:

{{1+5}}
{{'One' + 'Two'}}

Based on those expressions, the web page displays these values:

6
OneTwo

Expressions are bound to the data model, which provides two huge benefits. First, you can use the property names and functions that are defined in the scope inside your expressions. Second, because the expressions are bound to the scope, when data in the scope changes, so do the expressions. For example, suppose that the scope contains the following values:

$scope.name='Brad';
$scope.score=95;

You can directly reference the name and score values in the template expressions, as shown here:

Name: {{name}}
Score: {{score}}
Adjusted: {{score+5}}

angularjs expressions are similar to JavaScript expressions in several ways, but they differ in these ways:

Recommended :  Configuring user authorization in yii framework

ImageAttribute evaluation: Property names are evaluated against the scope model instead of against the global JavaScript namespace.

ImageMore forgiving: Expressions do not throw exceptions when they encounter undefined or null variable types; instead, they treat these as having no value.

ImageNo flow control: Expressions do not allow JavaScript conditionals or loops. Also, you cannot throw an error inside an expression.

angularjs evaluates the strings used to define the value of attributes in directive tags as expressions. This enables you to include expression-type syntax within a definition. For example, when you set the value of the ng-click directive in the template, you specify an expression. Inside that expression, you can reference scope variable and use other expression syntax, as shown here:

<span ng-click="scopeFunction()"></span>
<span ng-click="scopeFunction(scopeVariable, 'stringParameter')"></span>
<span ng-click="scopeFunction(5*scopeVariable)"></span>

Because the angularjs template expressions have access to the scope, you can also make changes to the scope inside the angularjs expression. For example, the following ng-click directive changes the value of msg inside the scope model:

<span ng-click="msg='clicked'"></span>

Using Basic Expressions

In this exercise you get a chance to see how angularjs expressions handle rendering of strings and numbers. The purpose of this exercise is to illustrate how angularjs evaluates expressions that contain strings and numbers as well as basic mathematical operators.

Recommended :  Retrieve data from Google Analytics in laravel 5.1

The code in  is just a simple angularjs application with a controller named myController. The controller is empty because none of the expressions accesses the scope.

The code in  is an angularjs template that contains several types of expressions wrapped in {{}} brackets. Some of the expressions are just numbers or strings, some include the + operation to combine strings and/or numbers, and one applies a === operator to compare two numbers.

shows the rendered web page. Note that numbers and strings are rendered directly to the final view. Adding strings and numbers together enables you to build text strings that are rendered to the view. Also note that using a comparison operator renders the word true or false to the view.

expressions_basic.js: Basic angularjs Application Code with Empty Controller

01 angular.module('myApp', [])
02   .controller('myController', function($scope) {
03   });

Listing 5.2 expressions_basic.html: Applying Basic Strings and Numbers with Simple Math Operations to an angularjs Template

 <!doctype html>
 <html ng-app="myApp">
  <head>
    <title>angularjs Expressions</title>
     <style>
       p{margin:0px;}
      p:after{color:red;}
    </style>
  </head>
  <body>
     <div ng-controller="myController">
       <h1>Expressions</h1>
       Number:<br>
      {{5}}<hr>
      String:<br>
       {{'My String'}}<hr>
      Adding two strings together:<br>
      {{'String1' + ' ' + 'String2'}}<hr>
       Adding two numbers together:<br>
      {{5+5}}<hr>
      Adding strings and numbers together:<br>
       {{5 + '+' + 5 + '='}}{{5+5}}<hr>
       Comparing two numbers with each other:<br>
      {{5===5}}<hr>
 <script src="http://code.angularjs.org/1.3.0/angular.min.js"></script>
    <script src="js/expressions_basic.js"></script>
  </body>
 </html>
prevChapter 1 of 2

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares