Search

Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-based MVW (Model View Whatever) Framework. One of the most popular open-source web application frameworks, Angular has been super-powered by Google since 2010. It is a toolset used for building the framework most suited to single page application development; but can also be utilized to work for other categories of web pages. Fully extensible, Angular works well with other web-based libraries. All its features can be modified and can even be replaced to suit your unique development workflow and web feature needs.   Since AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal <script> tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from https://angularjs.org/. If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Expressions in the following section. Introduction  Expressions In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and returns the result exactly where the expression is written. We will learn about each type of Expression in detail. The topics we will go through in this article are: Introduction to Expressions AngularJS Examples AngularJS using Numbers AngularJS using Strings AngularJS using Objects AngularJS using Arrays AngularJS Expression Capabilities and Limitations. Expressions in AngularJS Expressions are used to bind application data to html, and are written inside double braces in this manner: {{ expression}}. They behave in the same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and output the data where they are used. They have the following qualities: Can be written inside double braces: {{ expression }}. Can also be written inside a directive: ng-bind="expression". AngularJS will resolve the expression, and return the result exactly where the expression is written. Much like JavaScript expressions, they can contain literals, operators, and variables. Example {{ 5 + 5 }} or {{ firstName + " " + lastName }} * Note: The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable or expression changes, the content of the specified HTML element will be changed as well. AngularJS Expressions and JavaScript expressions Let us compare Expressions in AngularJS and JavaScript. Similarity between AngularJS Expressions and JavaScript expressions: AngularJS expressions and JavaScript expressions can both contain literals, operators and variables. Differences between AngularJS Expressions and JavaScript expressions: Context: JavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object. AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs. Instead use services like $window and $location in functions on controllers, which are then called from expressions. Such services provide mockable access to globals. It is possible to access the context object using the identifier this and the locals object using the identifier $locals. AngularJS does not use JavaScript's eval() to evaluate expressions. Instead AngularJS's $parse service processes these expressions. Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In AngularJS, expression evaluation is forgiving to undefined and null. In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general-purpose language, the expression evaluations are primarily used for data binding, which often look like this: {{a.b.c}} It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving, we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}} Similarly, invoking a function a.b.c() on undefined or null simply returns undefined. Filters: You can use filters within expressions to format data before displaying it. No Control Flow Statements: You cannot use the following in an AngularJS expression: conditionals, loops, or exceptions. Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the AngularJS philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive. No RegExp Creation with Literal Notation: You cannot create regular expressions in an AngularJS expression. An exception to this rule is ng-pattern which accepts valid RegExp. No Object Creation with New Operator: You cannot use new operator in an AngularJS expression. No Bitwise, Comma, And Void Operators: You cannot use Bitwise, or void operators in an AngularJS expression. Citation: https://docs.angularjs.org/guide/expression (Docs from AngularJS) Thus, summarizing the JavaScript and AngularJS Expressions, we get the following main points: AngularJS expressions can be written inside HTML, while JavaScript expressions cannot. AngularJS expressions support filters, while JavaScript expressions do not. AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do. AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc. AngularJS expression cannot declare functions. AngularJS expression cannot contain comma or void. AngularJS expression cannot contain return keyword. There are several categories in which Expressions operate. Some of the Expression Types are: Expressions Using numbers. Example: <p>Expense on Books : {{cost * quantity}} Rs</p> Expressions Using strings. Example: <p>Hello {{student.firstname + " " + student.lastname}}!</p> Expressions Using object. Example: <p>Roll No: {{student.rollno}}</p> Expressions Using array. Example: <p>Marks(Math): {{marks[3]}}</p> Let us go through each category in detail. Expression using Numbers Expression using numbers states that if any expression is using the number as variable or constant and the operators (like +, -, *, /, %, etc.) then those expressions are called number expressions.   Say if we use the expression as:               <p>My first expression: {{ 5 + 5 }}</p> Then AngularJS will understand that this is a number expression. It will evaluate the expression and result in:              My first expression: 10 We will understand more about the use of number expression in AngularJS with examples. Example: Considering you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js Example Using Curly Braces {{ }} for expressions: <!DOCTYPE html>  <html>  <head>  <title>Number Expression of AngularJs</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.expr1 = 10;  $scope.expr2 = 20  });  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <div>Number Expression</div>  <p>The Result of Addition is : {{expr1 + expr2}}</p>  </div>  </form>  </body>  </html> Now run the number expressions as an HTML file and check the output, which will look like this:Example Using ng-init and ng-bind for number expressions: <!DOCTYPE html>  <html>  <head>  <title>Number Expression of AngularJs</title>  <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js">  </script>   </head>  <body>  <div ng-app="" ng-init="expr1=10; expr2=20">  <form id="form1">    <p>  The Result of Addition is :    <div ng-bind="expr1 + expr2"></div>  </p>    </form>  </div>  </body>  </html> Now run the number expressions with ng-init and ng-bind as an HTML file and check the output, which will look like this: Expression using String Expression using String in AngularJS is a unit of code to perform operations on string values like + operator for concatenation of String, or the angular.isString() function.   * Note: The angular.isString() function in AngularJS is used to determine whether the parameter inside isString function is a string or not. It returns true if the reference is a string; and otherwise returns false.  For example: var obj1 = 123;   var obj2 = "A String value";   $scope.isString1 = angular.isString(obj1);   $scope.isString2 = angular.isString(obj2);  isString1 returns false while isString2 returns true. We will see how to use string expressions in detail in AngularJS with the following example: Example: <!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.expr1 = "Hello ";  $scope.expr2 = "World";  $scope.expr3 = 100;  var nexpr = $scope.expr3;  var sexpr = $scope.expr1;  $scope.isString1 = angular.isString(sexpr);  $scope.isString2 = angular.isString(nexpr);  });  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <div>String Expression</div>  <p>  The Result of Concatenation of {{expr1}} and {{expr2}} is :   {{expr1 + expr2}}  </p>  <p>  The Result of angular.isString() for parameter   {{expr1}} is : {{isString1}}  </p>  <p>  The Result of angular.isString() for parameter   {{expr3}} is : {{isString2}}  </p>  </div>  </form>  </body>  </html> Now run the String expressions as an HTML file and check the output, which will look like this: Expression using Object The object expressions in AngularJS hold object properties in them. AngularJS Objects and their fields are then evaluated at the view where they are used. For understanding AngularJS Objects, let’s go through the following section:  Objects in AngularJS Before moving forth we need to understand objects in AngularJS.  AngularJS objects are the same as JavaScript objects, and consist of a name-value pair. AngularJs objects have two parts: the object name and the object definition. The object name is the name by which we identify the object. The object definition consists of field to value pair, which defines the complete object. For Example: Considering an object as AngularTraining with fields as Trainer, noOfStd, noOfHours, it can be defined as: $scope.AngularTraining = {  Trainer: ‘Monica’,  noOfStd: 10,  noOfHours: 24  };  To use an object, we use  a .(dot) operator. Eg: to get the name of the trainer in the above example, we identify by AngularTraining.Trainer which gives a value of Monica in this case. Note that $scope in AngularJS is a built-in object which basically binds the “controller” and the “view”. One can define member variables in the $scope within the controller which can later be accessed by the view. We will see how to use object expressions in detail in AngularJS with the following example: Example: <!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.AngularTraining = {  Trainer: 'Monica',  noOfStd: 10,  noOfHours: 24  };   });  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <div>  <p>  Pure JSON object contains key value pairs as Object Expression  </p>  </div>  <p>  The AngularTraining Object is:  <br/>  AngularTraining.Trainer: {{ AngularTraining.Trainer}}   <br/>  AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}   <br/>  AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}    </p>  </div>  </form>  </body>  </html> Now run the Object expressions as an HTML file and check the output, which will look like this:Objects with ng-init definition: We can define the objects at ng-init as shown in the following example: <!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  </head>  <body>  <form id="form1">  <div div ng-app="" ng-init = " AngularTraining = { Trainer: 'Monica',  noOfStd: 10, noOfHours: 24 }" >  <div>  <p>  Pure JSON object contains key value pairs as Object Expression  </p>  </div>  <p>  The AngularTraining Object is:  <br/>  AngularTraining.Trainer: {{ AngularTraining.Trainer}}   <br/>  AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}   <br/>  AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}    </p>  </div>  </form>  </body>  </html> Now run the Object expressions as an HTML file and check the output, which will look like this: Expression using Array Arrays in AngularJS are the variables that hold a group of data just like any other programming language. The Expressions using Arrays evaluate these array objects and provide the output. Arrays in AngularJS An array is a group of values with a group name, with the values separated by commas.  An array is a special data type which can store multiple values of different data types sequentially using a special syntax. For example: marks = [95, 52, 65, 98, 55, 35]; We will see how to use array expressions in AngularJS with the following example: Example: <!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  <script>  var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {  $scope.name = "Monica";  $scope.leave = [1, 2, 0];  });  </script>  </head>  <body ng-app="myApp">  <form id="form1">  <div ng-controller="myController">  <div>  <p>  Array Expression</p>  </div>  <p>  The Leave Report for the first quarter for Employee: <br/>  {{name}} is:  <br/>  January: {{ leave[0] }}   <br/>  February: {{ leave[1] }}    <br/>  March: {{ leave[2] }}    <br/>  Total Leave for the first Quarter is:  {{ leave[0] + leave[1] + leave[2] }}   </p>  </div>  </form>  </body>  </html> Now run the Array expressions as an HTML file and check the output, which will look like this:Defining Arrays with ng-init definition: We can define the arrays at ng-init as shown in the following example: <!DOCTYPE html>  <html>  <head>  <title>String Expressions of AngularJS</title>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>  </head>  <body >  <form id="form1">  <div div ng-app="" ng-init = " name = 'Monica'; leave = [1, 2, 0]; " >  <div>  <p>  Array Expression</p>  </div>  <p>  The Leave Report for the first quarter for Employee: <br/>  {{name}} is:  <br/>  January: {{ leave[0] }}   <br/>  February: {{ leave[1] }}    <br/>  March: {{ leave[2] }}    <br/>  Total Leave for the first Quarter is:  {{ leave[0] + leave[1] + leave[2] }}   </p>  </div>  </form>  </body>  </html> Now run the Array expressions as an HTML file and check the output, which will look like this: Complete Example Summarizing the different types of AngularJS Expressions, we can understand that numbers and strings can be evaluated, while objects and arrays are converted to either numbers or strings first and then evaluated in AngularJS A complete example of AngularJS expression is: <!DOCTYPE html>  <html>     <head>        <title>AngularJS Expressions</title>     </head>     <body>        <h1>Expression</h1>  <div ng-app = "" ng-init = "quantity = 2; cost = 30; student = {firstname: 'Monica', lastname: 'Gupta', rollno: 34}; marks = [80, 90, 75, 73, 80] ">  <p>Hello {{student.firstname + " " + student.lastname}}!</p>  <p>Expense on Books : {{cost * quantity}} Rs</p>  <p>Roll No: {{student.rollno}}</p>  <p>Marks(Math): {{marks[3]}}</p>  </div>  <script src = "angular.min.js"></script>  </body>   </html> Now run the Expressions as an HTML file and check the output, which will look like this: AngularJS Expression capabilities and Limitations AngularJS Expression capabilities Angular expressions have the same power and flexibility as JavaScript expressions.  In JavaScript, when you try to evaluate undefined properties or objects or arrays, it generates a ReferenceError or TypeError. However, in AngularJS, expressions evaluation is forgiving and it generates an undefined or null value. In AngularJS expressions you can use filters within expressions to format data before displaying it. Angular JS Expression limitations Unlike JavaScript expressions, there is currently no availability to use conditionals, loops, or exceptions in an AngularJS expression You cannot declare functions in an AngularJS expression, not even inside ng-init directive. You cannot create regular expressions in an AngularJS expression. A regular expression is a combination of symbols and characters, which are used to search for strings such as : . * \ $ etc. Such expressions cannot be used within AngularJS expressions. Also you cannot use Bitwise, comma (,) or void operators in an AngularJS expression. Conclusion (Summary) AngularJS Expressions are used to evaluate values out of Numbers, Number variable, String variable, Objects or Arrays. AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as <span title="{{ attrBinding }}">{{ textBinding }}</span>. Some valid expressions are: 1+2, a+b, user.name, items[index] . Thus, we can say that Expressions are variables which were evaluated in the double braces {{ }}. It can be number Expressions, String Expressions, Object Expressions or Array Expressions. Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

Learn AngularJs Expressions With Examples

9K
  • by Monica Gupta
  • 19th Sep, 2020
  • Last updated on 20th Oct, 2020
  • 9 mins read
Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-based MVW (Model View Whatever) Framework. One of the most popular open-source web application frameworks, Angular has been super-powered by Google since 2010. It is a toolset used for building the framework most suited to single page application development; but can also be utilized to work for other categories of web pages. Fully extensible, Angular works well with other web-based libraries. All its features can be modified and can even be replaced to suit your unique development workflow and web feature needs.   

Since AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal <script> tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  

AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. 

AngularJS can be downloaded from https://angularjs.org/. 

If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS. 

It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Expressions in the following section. 

Introduction  

Expressions 

In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and returns the result exactly where the expression is written. 

We will learn about each type of Expression in detail. 

The topics we will go through in this article are: 

  • Introduction to Expressions 
  • AngularJS Examples 
  • AngularJS using Numbers 
  • AngularJS using Strings 
  • AngularJS using Objects 
  • AngularJS using Arrays 
  • AngularJS Expression Capabilities and Limitations. 

Expressions in AngularJS 

Expressions are used to bind application data to html, and are written inside double braces in this manner: {{ expression}}. They behave in the same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and output the data where they are used. They have the following qualities: 

  • Can be written inside double braces: {{ expression }}. 
  • Can also be written inside a directive: ng-bind="expression". 
  • AngularJS will resolve the expression, and return the result exactly where the expression is written. 
  • Much like JavaScript expressions, they can contain literals, operators, and variables. 

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }} 

* Note: The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable or expression changes, the content of the specified HTML element will be changed as well. 

AngularJS Expressions and JavaScript expressions 

Let us compare Expressions in AngularJS and JavaScript. 

Similarity between AngularJS Expressions and JavaScript expressions: 

  • AngularJS expressions and JavaScript expressions can both contain literals, operators and variables. 

Differences between AngularJS Expressions and JavaScript expressions: 

  • ContextJavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object. 
    • AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs. 
    • Instead use services like $window and $location in functions on controllers, which are then called from expressions. Such services provide mockable access to globals. 
    • It is possible to access the context object using the identifier this and the locals object using the identifier $locals. 
    • AngularJS does not use JavaScript's eval() to evaluate expressions. Instead AngularJS's $parse service processes these expressions. 
  • Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In AngularJS, expression evaluation is forgiving to undefined and null. 
    • In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general-purpose language, the expression evaluations are primarily used for data binding, which often look like this: {{a.b.c}} 
    • It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving, we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}} 
    • Similarly, invoking a function a.b.c() on undefined or null simply returns undefined. 
  • FiltersYou can use filters within expressions to format data before displaying it. 
  • No Control Flow Statements: You cannot use the following in an AngularJS expression: conditionals, loops, or exceptions. 
    • Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the AngularJS philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. 
  • No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive. 
  • No RegExp Creation with Literal Notation: You cannot create regular expressions in an AngularJS expression. An exception to this rule is ng-pattern which accepts valid RegExp. 
  • No Object Creation with New Operator: You cannot use new operator in an AngularJS expression. 
  • No Bitwise, Comma, And Void OperatorsYou cannot use Bitwise, or void operators in an AngularJS expression. 

Citation: https://docs.angularjs.org/guide/expression (Docs from AngularJS) 

Thus, summarizing the JavaScript and AngularJS Expressions, we get the following main points: 

  • AngularJS expressions can be written inside HTML, while JavaScript expressions cannot. 
  • AngularJS expressions support filters, while JavaScript expressions do not. 
  • AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do. 
  • AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc. 
  • AngularJS expression cannot declare functions. 
  • AngularJS expression cannot contain comma or void. 
  • AngularJS expression cannot contain return keyword. 

There are several categories in which Expressions operate. Some of the Expression Types are: 

  • Expressions Using numbers. Example: 
    • <p>Expense on Books : {{cost * quantity}} Rs</p> 
  • Expressions Using strings. Example: 
    • <p>Hello {{student.firstname + " " + student.lastname}}!</p> 
  • Expressions Using object. Example: 
    • <p>Roll No: {{student.rollno}}</p> 
  • Expressions Using array. Example: 
    • <p>Marks(Math): {{marks[3]}}</p> 

Let us go through each category in detail. 

Expression using Numbers 

Expression using numbers states that if any expression is using the number as variable or constant and the operators (like +, -, *, /, %, etc.) then those expressions are called number expressions.   

Say if we use the expression as: 

              <p>My first expression: {{ 5 + 5 }}</p> 

Then AngularJS will understand that this is a number expression. It will evaluate the expression and result in: 

             My first expression: 10 

We will understand more about the use of number expression in AngularJS with examples. 

Example: 

Considering you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js 

Example Using Curly Braces {{ }} for expressions: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Number Expression of AngularJs</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.expr1 = 10; 
$scope.expr2 = 20 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div>Number Expression</div> 
<p>The Result of Addition is : {{expr1 + expr2}}</p> 
</div> 
</form> 
</body> 
</html> 

Now run the number expressions as an HTML file and check the output, which will look like this:

Learn AngularJs Expressions With Examples

Example Using ng-init and ng-bind for number expressions: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Number Expression of AngularJs</title> 
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"> 
</script>  
</head> 
<body> 
<div ng-app="" ng-init="expr1=10; expr2=20"> 
<form id="form1">   
<p> 
The Result of Addition is :  
 <div ng-bind="expr1 + expr2"></div> 
</p>   
</form> 
</div> 
</body> 
</html> 

Now run the number expressions with ng-init and ng-bind as an HTML file and check the output, which will look like this: Learn AngularJs Expressions With Examples

Expression using String 

Expression using String iAngularJS is a unit of code to perform operations on string values like + operator for concatenation of String, or the angular.isString() function.   

* Note: The angular.isString() function in AngularJS is used to determine whether the parameter inside isString function is a string or not. It returns true if the reference is a string; and otherwise returns false.  

For example: 

var obj1 = 123;  
var obj2 = "A String value";  
$scope.isString1 = angular.isString(obj1);  
$scope.isString2 = angular.isString(obj2); 
isString1 returns false while isString2 returns true. 

We will see how to use string expressions in detail in AngularJS with the following example: 

Example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.expr1 = "Hello "; 
$scope.expr2 = "World"; 
$scope.expr3 = 100; 
var nexpr = $scope.expr3; 
var sexpr = $scope.expr1; 
$scope.isString1 = angular.isString(sexpr); 
$scope.isString2 = angular.isString(nexpr); 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div>String Expression</div> 
<p> 
The Result of Concatenation of {{expr1}} and {{expr2}} is :  
{{expr1 + expr2}} 
</p> 
<p> 
The Result of angular.isString() for parameter  
{{expr1}} is : {{isString1}} 
</p> 
<p> 
The Result of angular.isString() for parameter  
{{expr3}} is : {{isString2}} 
</p> 
</div> 
</form> 
</body> 
</html> 

Now run the String expressions as an HTML file and check the output, which will look like this:
Learn AngularJs Expressions With Examples

Expression using Object 

The object expressions in AngularJS hold object properties in themAngularJS Objects and their fields are then evaluated at the view where they are used. For understanding AngularJS Objects, let’s go through the following section:  

Objects in AngularJS 

Before moving forth we need to understand objects in AngularJS.  AngularJS objects are the same as JavaScript objects, and consist of a name-value pair. 

AngularJs objects have two parts: the object name and the object definition. The object name is the name by which we identify the object. The object definition consists of field to value pair, which defines the complete object. 

For Example: Considering an object as AngularTraining with fields as Trainer, noOfStdnoOfHours, it can be defined as: 

$scope.AngularTraining = { 
TrainerMonica, 
noOfStd10, 
noOfHours24 
};  

To use an object, we use  a .(dot) operator. Eg: to get the name of the trainer in the above example, we identify by AngularTraining.Trainer which gives a value of Monica in this case. 

Note that $scope in AngularJS is a built-in object which basically binds the controller and the view. One can define member variables in the $scope within the controller which can later be accessed by the view. 

We will see how to use object expressions in detail in AngularJS with the following example: 

Example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.AngularTraining = { 
Trainer: 'Monica', 
noOfStd: 10, 
noOfHours: 24 
};  
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div> 
<p> 
Pure JSON object contains key value pairs as Object Expression 
</p> 
</div> 
<p> 
The AngularTraining Object is: 
<br/> 
AngularTraining.Trainer{{ AngularTraining.Trainer}}  
<br/> 
AngularTraining.noOfStd{{ AngularTraining. noOfStd}}  
<br/> 
AngularTraining. noOfHours{{ AngularTraining. noOfHours}}  
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Object expressions as an HTML file and check the output, which will look like this:Learn AngularJs Expressions With Examples

Objects with ng-init definition: 

We can define the objects at ng-init as shown in the following example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
</head> 
<body> 
<form id="form1"> 
<div div ng-app="" ng-init = " AngularTraining = { Trainer'Monica',  noOfStd: 10, noOfHours: 24 }" > 
<div> 
<p> 
Pure JSON object contains key value pairs as Object Expression 
</p> 
</div> 
<p> 
The AngularTraining Object is: 
<br/> 
AngularTraining.Trainer{{ AngularTraining.Trainer}}  
<br/> 
AngularTraining.noOfStd{{ AngularTraining. noOfStd}}  
<br/> 
AngularTraining. noOfHours{{ AngularTraining. noOfHours}}  
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Object expressions as an HTML file and check the output, which will look like this: Learn AngularJs Expressions With Examples

Expression using Array 

Arrays in AngularJS are the variables that hold a group of data just like any other programming language. The Expressions using Arrays evaluate these array objects and provide the output. 

Arrays in AngularJS 

An array is a group of values with a group name, with the values separated by commas.  An array is a special data type which can store multiple values of different data types sequentially using a special syntax. 

For example: 

marks = [95, 52, 65, 98, 55, 35]; 

We will see how to use array expressions in AngularJS with the following example: 

Example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.name = "Monica"; 
$scope.leave = [120]; 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div> 
<p> 
Array Expression</p> 
</div> 
<p> 
The Leave Report for the first quarter for Employee: <br/> 
{{name}} is: 
<br/> 
January{{ leave[0] }}  
<br/> 
February{{ leave[1] }}   
<br/> 
March{{ leave[2] }}   
<br/> 
Total Leave for the first Quarter is: 
{{ leave[0] + leave[1] + leave[2] }} 
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Array expressions as an HTML file and check the output, which will look like this:

Learn AngularJs Expressions With Examples

Defining Arrays with ng-init definition: 

We can define the arrays at ng-init as shown in the following example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
</head> 
<body > 
<form id="form1"> 
<div div ng-app="" ng-init = " name = 'Monica'; leave = [120]; " > 
<div> 
<p> 
Array Expression</p> 
</div> 
<p> 
The Leave Report for the first quarter for Employee: <br/> 
{{name}} is: 
<br/> 
January{{ leave[0] }}  
<br/> 
February{{ leave[1] }}   
<br/> 
March{{ leave[2] }}   
<br/> 
Total Leave for the first Quarter is: 
{{ leave[0] + leave[1] + leave[2] }} 
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Array expressions as an HTML file and check the output, which will look like this: 

Learn AngularJs Expressions With Examples

Complete Example 

Summarizing the different types of AngularJS Expressions, we can understand that numbers and strings can be evaluated, while objects and arrays are converted to either numbers or strings first and then evaluated in AngularJS 

A complete example of AngularJS expression is: 

<!DOCTYPE html> 
<html>    
<head>       
<title>AngularJS Expressions</title>    
</head> 
   <body>       
<h1>Expression</h1> 
<div ng-app = "" ng-init = "quantity = 2; cost = 30; student = {firstname: 'Monica', lastname: 'Gupta', rollno: 34}; marks = [80, 90, 75, 73, 80] "> 
<p>Hello {{student.firstname + " " + student.lastname}}!</p> 
<p>Expense on Books : {{cost * quantity}} Rs</p> 
<p>Roll No: {{student.rollno}}</p> 
<p>Marks(Math): {{marks[3]}}</p> 
</div> 
<script src = "angular.min.js"></script> 
</body>  
</html> 

Now run the Expressions as an HTML file and check the output, which will look like this: Learn AngularJs Expressions With Examples

AngularJS Expression capabilities and Limitations 

AngularJS Expression capabilities 

  • Angular expressions have the same power and flexibility as JavaScript expressions.  
  • In JavaScript, when you try to evaluate undefined properties or objects or arrays, it generates a ReferenceError or TypeError. However, in AngularJS, expressions evaluation is forgiving and it generates an undefined or null value. 
  • In AngularJS expressions you can use filters within expressions to format data before displaying it. 

Angular JS Expression limitations 

  • Unlike JavaScript expressions, there is currently no availability to use conditionals, loops, or exceptions in an AngularJS expression 
  • You cannot declare functions in an AngularJS expression, not even inside ng-init directive. 
  • You cannot create regular expressions in an AngularJS expression. A regular expression is a combination of symbols and characters, which are used to search for strings such as : . * \ $ etc. Such expressions cannot be used within AngularJS expressions. 
  • Also you cannot use Bitwise, comma (,) or void operators in an AngularJS expression. 

Conclusion (Summary) 

AngularJS Expressions are used to evaluate values out of Numbers, Number variable, String variable, Objects or Arrays. 

AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as <span title="{attrBinding }}">{{ textBinding }}</span>. 

Some valid expressions are: 1+2, a+b, user.name, items[index] . 

Thus, we can say that Expressions are variables which were evaluated in the double braces {{ }}. It can be number Expressions, String Expressions, Object Expressions or Array Expressions. 


Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

Monica

Monica Gupta

Author

I am Monica Gupta with 19+ years of experience in the field of Training and Development. I have done over 500 Corporate Trainings. I am currently working as a freelancer for several years. My core area of work is Java, C++, Angular, PHP, Python, VBA.

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

What Is Dependency Injection in AngularJS

AngularJS is an open source JavaScript MVW (Model View Whatever) framework backed by Google and is widely popular for creating dynamic apps. It offers a suite of tools that can be used for building the framework most suited to your single page application development. However, it can also be fully utilized to work for other categories of web pages. It works well with other web-based libraries and is fully extensible. All its features can be modified and even can be replaced to suit your unique development workflow and web feature needs.    As AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal  tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from https://angularjs.org/. If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Dependency Injection in the following section. IntroductionDependency Injection − AngularJS has a built-in dependency injection (DI) subsystem library whose work is to help the development team by making the application easier to develop, test, and understand. We will learn about each part of DI in detail. The topics we will go through in this article are: Dependency injection in AngularJS Value Injecting a Value Factory Injecting Values into a Factory Service Injecting Values into a Service Providers Configuring a Provider Constants Dependencies Between Modules Dependency injection in AngularJs Today’s software is totally designed in accordance with various design patterns. One such pattern is Dependency Injection. The DI design pattern specifies the pattern in which components are provided with their dependencies, instead of hard coding them within the component. AngularJS comes with a built-in dependency injection mechanism that enables you to divide your application into various types of components which can be injected into each other as their respective dependencies. Modularization of your application makes it easier to use, reuse, configure and even test the different components in your application. According to DI the core types of objects and components include the following: Value Factory Service Provider Constant These are the objects and components which can be injected into each other using AngularJS Dependency Injection. ValueFor AngularJS, the “Value” is a simple object. It can be a number, a string or a POJO (Plain old JavaScript object). This object is used to pass values in AngularJS factories, AngularJS services or AngularJS controllers during the run and config phase. The following example shows the steps involved in using a value. Step 1:  Define a module   var myMod = angular.module("myModule", []); Here, myModule is created using the AngularJS function angular.module(). You can add value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a value object and pass data to it.    myMod.value("numberValue", 10);    myMod.value("stringValue", "aaa");    myMod.value("objectValue", { field1 : 123, field2 : "abc"} );  Here, values are defined using the value () function on the module as created in step 1. The first parameter specifies the name of the value, and the second parameter is the value itself passed to other parts of the application. Factories, services and controllers can now reference these values by their value name. Step 3: Injecting a value in Controller function To inject a value into AngularJS controller function, we need to add a parameter with the same value name as that with which the value was defined. Note that the controller function is registered in angular via the angular.module(...).controller(...) function call. The $scope parameter passed to the controller function is the model for the controller. Thus, here myMod is the module registering the controller as myController, and $scope is the model for myController.  var myMod = angular.module("myModule", []);    myMod.value("numberValue", 10);    myMod.controller("myController", function($scope, numberValue) {     console.log(numberValue);    });Example: Using Value in AngularJS: Consider that you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJs CDN for the same provided by Google.          Value in AngularJS             Value Example     The numberValue is: {{nValue}}        var myMod = angular.module('myModule', []);  myMod.value("numberValue", 5);  myMod.controller('myController', function($scope, numberValue)   {  $scope.nValue =numberValue;  });       Output: Factory In AngularJS, a factory is a function that is used to return a value. This function creates the value on demand whenever a service or controller needs any value injected from the factory. AngularJS applications normally use a factory function to calculate and return a value. The following example shows the steps involved in using a Factory. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a factory object and return data from it.    myMod.factory("myFactory", function() {        return "a value";    }); Here, we have used the factory function to create a Factory named myFactory. This Factory is returning “a value” from it. Step 3: Injecting values into factory Create a controller which gets the factory created value injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a factory value into AngularJS controller function, we need to add a parameter with the same value name as that with which the factory was defined.  var myMod = angular.module("myModule", []);    myMod.factory("myFactory", function() {        return "a value";    });  myMod.controller("MyController", function($scope, myFactory) {    console.log(myFactory);    }); Note: It is not the factory function that is injected, but the value produced by the factory function that gets injected. Example: Using Factory in AngularJS:         Factory                Factory Example    The numberFactory is: {{nFactory}}        var myMod = angular.module('myModule', []);  myMod.factory("myFactory", function() {    return "a value";    });        myMod.controller('myController', function($scope, myFactory) {  $scope. nFactory =myFactory;  });       Output: Service Web Services are helpful functions that perform a task. Similarly, in AngularJS, Service is a JavaScript object which contains a set of functions to perform certain tasks. Services are created by using service() function on a module and then injecting it into controllers. The following example shows the steps involved in using a Service. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a service for defining the MathService for calculating basic math functions like add, subtract, multiply and divide. And then create another service, myService for defining a cube method to return the cube of a given number: myMod.service('MathService', function() {      this.add = function(a, b) { return a + b };      this.subtract = function(a, b) { return a - b };      this.multiply = function(a, b) { return a * b };      this.divide = function(a, b) { return a / b };  });  myMod.service('myService', function(MathService){       this.cube = function(a) {          return MathService.multiply(a,MathService.multiply(a,a));        }    }); The above code snippet uses MathService to call multiply function that takes two parameters and calculates the product.  Step 3: Inject the service "myService" into the controller   Create a controller which gets the Service injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a Service function into AngularJS controller function, we need to add a parameter with the same value name as that with which the Service was defined.  myMod.controller('myController', function($scope, myService) {        $scope.doCube = function() {          $scope.result = myService.cube($scope.number);       }    }); Here we can even make it event based by adding an event in the main HTML content as:   Enter a number:            Cube      Result of Service: {{result}}      Example: Using Service in AngularJS:         Service Example           Service Example        Result of Service: {{result}}          var myMod = angular.module("myModule", []);  myMod.service('myService', function(){  this.sum = function(a,b) {  return a + b;  }      });  myMod.controller('myController', function($scope, myService) {  $scope.result = myService.sum (5, 6);  });       Output: Provider In AngularJS, a provider is used to internally create other values or services or factory during config phase (the phase during which AngularJS bootstraps itself). Provider can be considered to be the most flexible form of factory you can create. Provider is a special factory method with a get() function which is used to return the value or service or factory. The following example shows the steps involved in using a Provider. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a service using provider which defines a method square to return the square of a number.  We use provider method to create a Provider.   myMod.config(function($provide) {       $provide.provider('myServiceProvider', function() {          this.$get = function() {             var factory = {};               factory.multiply = function(a, b) {                return a * b;              }             return factory;          };       });    });  Step 3: Inject the Provider "myServiceProvider" into the controller   Create a controller which gets the Provider injected (To understand how to create a Controller, go to the Value part of the article and navigate to its Step 3). To inject a Provider function into AngularJS controller function, we need to add a parameter with the same value name as that with which the provider was defined.  myMod.controller('myController', function($scope, myServiceProvider, defaultInput) {        $scope.number = defaultInput;        $scope.result = myServiceProvider.multiply($scope.number, $scope.number);        $scope.square = function() {               $scope.result = myServiceProvider.multiply($scope.number, $scope.number);         }       });   Example: Using Provider in AngularJS:             Provider               Provider Example                        Enter a number:      X 2              Result: {{result}}                                  var myMod  = angular.module("myModule", []);              myMod.config(function($provide) {    $provide.provider('myServiceProvider', function() {    this.$get = function() {    var factory = {};    factory.multiply = function(a) {     return a * a;          }  return factory;      };        });      });             myMod.value("defaultInput", 10);             myMod.controller('myController', function($scope, myServiceProvider, defaultInput) {                $scope.number = defaultInput;                $scope.result = myServiceProvider.multiply($scope.number);    $scope.square = function() {    $scope.result = myServiceProvider.multiply($scope.number);     }        });               Output: Constants Config Phase of AngularJS has some restrictions for injected values, as you cannot inject values into the module.config() function. Instead constants are used to pass values at config phase. To define a constant value we use the constant() function of the defined module. Then for the constant parameter we provide a constant value. The following example shows the steps involved in using a Constant in AngularJS. Step 1: Define a module   var myMod = angular.module("myModule", []);  Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a constant using the constant function and pass constant data to it.      myMod.constant("configParam", "constant value");    Example: Using Constant in AngularJS:              Constant            Constant Example      The numberConstant is:  {{nConstant}}            var myMod = angular.module('myModule', []);      myMod.constant("nConst", 5);      myMod.controller('myController', function($scope,nConst) {  $scope.nConstant =nConst;  });        Output: Difference between Constant and Value Values and Constants seem to be applied in the same way; however, Value differs from Constant in that value cannot be injected into configurations, but it can be intercepted by decorators. Also, a Constant can be used during the apps config phase, whereas a Value is only available during the run phase. The main difference between value and constant is that a value specified using Constant is available during the configuration phase while value specified using Value is available during the run phase. Example showing the difference between a Constant and a Value:          Constant                  Constant Example    {{ID}}          var myMod = angular.module('myModule', []);  myMod.value("myValue", "First Assignment");  myMod.value("myValue", "Second  Assignment");  myMod.constant("myConstant", "First Assignment");  myMod.constant("myConstant", "Second Assignment");  myMod.controller("myController", function($scope, myValue, myConstant) {  console.log("myValue: " + myValue);  console.log("myConstant: " + myConstant);  $scope.ID = " myValue: " + myValue + "&nbsp   myConstant: " + myConstant;  });       Output: Constant Example myValue: Second Assignment myConstant: First Assignment  Complete Example: AngularJS Dependency Injection Let's take an example to deploy all the above mentioned directives.                AngularJS Dependency Injection                 AngularJS Application Showing Dependency Injection         Enter a number:         X  2                Result: {{result}}                          var myMod = angular.module("myMod", []);    myMod.config(function($provide) {    $provide.provider('MathService', function() {    this.$get = function() {    var factory = {};    factory.multiply = function(a, b) {    return a * b;          }    return factory;      };        });      });    myMod.value("defaultInput", 10);    myMod.factory('MathService', function() {                var factory = {};                factory.multiply = function(a, b) {    return a * b;  }    return factory;  });           myMod.service('CalcService', function(MathService){    this.square = function(a) {    return MathService.multiply(a,a);     }         });    myMod.controller('myController', function($scope, CalcService, defaultInput) {    $scope.number = defaultInput;    $scope.result = CalcService.square($scope.number);    $scope.square = function() {    $scope.result = CalcService.square($scope.number);      }        });               Output: ConclusionIn the above article we learned about the Dependency Injection in AngularJS. Dependency Injection is a software design pattern that specifies how components get hold of their dependencies. In this pattern, components are given their dependencies instead of coding them directly within the component. We learned about core types of objects and components like Value, Factory, Service, Provider, and Constant. We learned how to create and register an injectable service and configure an injector with a service provider. We learned how to work with Injecting services to a controller. In the end we summarized with a complete example how Providers, Services, Factory and Value can be used.  Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
6561
What Is Dependency Injection in AngularJS

AngularJS is an open source JavaScript MVW (M... Read More

Logging in AngularJS Applications Made Simple

What comes to mind, when you think of a JavaScript framework that can be used to build applications across platforms, achieve maximum speed with accelerated performance and ensure quick builds? Just AngularJS, isn’t it?  Powered by Google, Angular was developed as a framework to give you a toolset for powering your single page application development, work well with other web-based libraries and be fully extensible. All its features can be modified and even replaced to give you complete freedom in developing your own unique workflow.  As a pure JavaScript framework, Angular can be added to an HTML page with a normal tag with src attribute pointing to the source framework library. AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions.  AngularJS can be downloaded from https://angularjs.org/.  If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS.  It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, Logging and Internationalization. We will deal with Logging in the following section. IntroductionAngularJS includes a logging service called $log, which logs the messages to the client browser's console. The $log service includes different methods to handle the log for error, information, warning or debug information. It can be useful in debugging and auditing. This article will help you learn about each type of log. The topics we will go through in this article are: Introduction to logging Testing AngularJS Logging Application What Is Application Logging? Angular Logging: The Improved Approach Logging with AngularJS - extending the built-in logger $log in AngularJS Turn off logging in AngularJS  Introduction to logging AngularJS has an impressive and robust logging mechanism in-built through the $logService and $log injection.  The $log service includes different methods to log the error, information, warning or debug information. It can be useful in debugging and auditing.  The main purpose of all AngularJS logging services is to simplify debugging and troubleshooting. To reveal the location of the calls to $log in the JavaScript console; you can "blackbox" the AngularJS source in your favorite browser. To blackbox in the browser, go to the page, right click it, “Inspect” it in developer mode, and then read the console. Note: All browsers do not support blackboxing. AngularJS logs everything to the console, which is neither a robust or scalable solution. Sometimes, you need to be able to intercept the exceptions and do something extra. This could be as simple as adding extra information or sending all logs to the server/database. $log in AngularJS AngularJS programmers frequently use console.log to record errors or other informational messages in their applications. Although this is fine while debugging your application, yet it is not a best practice for production environment. As AngularJS is all about services, it is a better idea to create a logging service that you can call from other services and components due to some event which needs to be logged. In this logging service, you can still call console.log, but you can also modify the service later to record messages to store them in local storage or a database table via the Web API. Some methods that we will use for logging in AngularJS $log are: log();  to write a log message info(); to write an information message warn(); to write a warning message error(); to write an error message debug(); to write a debug message  The above methods are used for different categorizations of $log. Testing AngularJS Logging Application An Example of logging in AngularJS is: Considering you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js  Logging Example in AngularJS var app = angular.module('myApp', []) app.controller("myController", function ($log) {             $log.log('This is log.');             $log.error('This is error.');             $log.info('This is info.');             $log.warn('This is warning.');             $log.debug('This is debugging.');         }); Go to Inspect, through browser blackbox to see the Console for the different loggers.   Now run the logging example as an HTML file and check the output, which will look like this: Go to Inspect, through browser blackbox to see the Console for the different loggers. In the Inspect Window, go to Console, and see the result as: This is log. This is error. (In red font displayed with error icon) This is info. This is warning. (In brown font with warning icon) Here is a more complex example, which logs according to events generated as follows:       Logging Example in AngularJS      var app = angular.module('myApp', [])  app.controller("myController", ['$scope', '$log', function($scope, $log) {  $scope.$log = $log;  $scope.message = 'Hello World!';  }]);            Reload this page with open console, enter text and hit the log button...  Message:         log  warn  info  error         Now run the above logging example as an HTML file and check the output, which will look like this: Reload this page with open console, enter text and hit the log button... Message:Clicking the buttons accordingly will give the console information as: Hello World! log Hello World! warn (in brown font with warning icon) Hello World! info Hello World! error (in red font with error icon) The output snapshot: What Is Application Logging? For a long time, logs have been an essential part of troubleshooting application and infrastructure performance. They help in providing visibility of how our applications are running on each of the various infrastructure components. Log data contains information such as out of memory exception or hard disk errors or even simple divide by zero error. Within software development, application logging plays a vital role; as much as we’d like our software to be perfect, issues will always arise within a production environment. When they do, a good logging strategy becomes very crucial. An application log usually contains errors, warning, events and non-critical information when compared to an error log that usually contains only errors and critical warnings. The application log should contain all the information necessary for audit. Put in simple words, an application log is a file that contains information about events that have occurred or errors and warnings that may occur due to some malfunctioning within a software application. These events are logged out by the application and written into a file, console or Web API. Once logged, the events can be handled accordingly as they include errors and warnings as well as informational events. The types of information and format of messages found in an application log file will vary between applications. These variables aren’t determined by external guidelines or by the operating system we are working on, rather they are determined by  the developers of the software application who control what goes into the log file. They’re the ones making decisions about what events and information would be useful to log and how logging should be done. Many events will be specific to the source application and many others would require a timestamp. Thus, it is common for logged events to contain information such as timestamp, source, etc. to make them more useful. Here is some common information that you will generally get in application log messages: Context information: Context information is the background information that provides an insight into the state of the application at the time of the message. Timestamp: A timestamp is a specific piece of contextual information for tracking and correlating issues that relate to the time aspect. Log levels: Log labels help you calculate the level of importance for the information entries in your log file. Some of the frequently used levels include INFO, WARN, ERROR, MESSAGE, and LOG. Once you are familiar with logged messages you will find it easier to use them when you’re trying to analyze bugs and unexpected events. When developers use the word “logging,” they usually refer to application logging. However, there are other types of logging as well. To further clarify what application logging is, let us briefly look at other types of logs to understand the differences. System Logs: System logs are written by the operating system. They contain information about System Processes and Drivers. On a Windows machine, System log is stored in the event log while in a Linux machine this is the syslog service. Server Logs: Server logs provide information on the state of a web application, web API, web Server or application server. The web server or application server is responsible for creating and maintaining server log files. GC Logs: Garbage collector logs assist with memory management of Java Programming Language by tracking objects within a JVM (Java Virtual Machine) and removing those that are unused. They are deactivated by default, however with simple switches, they can be switched on. Thus, application logging involves recording information about your application’s runtime behavior to a more persistent medium like a file or a database or even simple console. By reading the log entries wherever they are stored, you go back in time to analyze the application’s behavior, understanding the sequence of events that happened to it. You could even repeat the actions taken by a user, in order to recreate and fix whatever problem you are struggling with.  We need to log so that we can retroactively debug and analyze our application as if we are running it in the current moment. AngularJS Logging: The Improved Approach It is very easy to log all of the client-side messages to the server using AngularJS logging services. The biggest benefit is that it makes it easier to find application errors once in production phase and accelerate bug finding at deployment stage. Client-side logging can also help you identify the frequency of errors so that hotfixes can be prioritized in the order of importance as they can be labeled, helping you further to improve your AngularJS application for your clients. In AngularJS we have the different categories of logging as : $log.log(), $log.warn(), $log.info(), $log.error() and $log.debug(). These help the programmer and debugger to understand and classify different information as simple log, warning, information, error or debug information. Logging with AngularJS - extending the built-in logger Showing the correct line numbers You can tell AngularJS to show the correct line numbers by binding the $log.* functions to the console.* functions. For Example:     $log.debug = console.debug.bind(console); You will have to do that for each one of the 5 $log methods separately. For Example:       Logging Example in AngularJS        var app = angular.module('myApp', [])  app.controller("myController", ['$scope', '$log', function($scope, $log) {  $log.debug = console.debug.bind(console);  $log.info = console.info.bind(console);  $log.log = console.log.bind(console);  $log.warn = console.warn.bind(console);  $log.error = console.error.bind(console);  console.debug("Calling console.debug");  console.info("Calling console.info");  console.log("Calling console.log");  console.warn("Calling console.warn");  console.error("Calling console.error");  $scope.$log = $log;  $scope.message = 'Hello World!';  }]);            Reload this page with open console, enter text and hit the log button...    Message:            log  warn  info  error  debug         Output is: All the console messages are shown in line numbers. Showing the  $exceptionHandler as Factory  As per https://cmatskas.com/logging-with-angularjs-extending-the-built-in-logger/  site:  AngularJs has an impressive and robust logging mechanism through the $logService and $log injection. However, Angular logs everything to the console, which is neither a robust or scalable solution. Sometimes, you need to be able to intercept the exceptions and do something extra. This could be as simple as adding extra information or sending all logs to the server/database. The example below is simple and allows you to hook into the $exceptionHandler and pass a logger in the form of an AngularJS factory. The factory contains only one method => log(). This method first calls the base $log.error() method and after that point we have all the data we need to do as we want. The only limitation is that this custom logger deals only with errors and exceptions. Example: var mod = angular.module("LogDemo2", [] ); mod.provider('$exceptionHandler', {      $get: function( errorLogService ) {          return( errorLogService );      }  });  mod.factory('errorLogService', ['$log', '$window', function($log, $window) {        function log( exception ) {            $log.error.apply( $log, arguments );            try {              var args = [];              if (typeof arguments === 'object') {                  for(var i = 0; i       Reload this page with open console, enter text and hit the log button...  Message:           log  warn  info  error  debug          Case 1:  With :   app.config(function($logProvider){  $logProvider.debugEnabled(false);  }); Output: We can see that if we open the “See Console Sidebar”, we get 1 error, 1 warning and 2 info(1 for log function, other one for info function). Here Debug() is missing as it is turned off by our application. If we hide the Console Sidebar, we can still see all the messages displayed in the Console as:Case 2: With :  app.config(function($logProvider){  $logProvider.debugEnabled(true);  }); Or we can skip the entire code for app.config(){….}); as by default debug is turned on. Output: We can see that if we open the “See Console Sidebar”, we get 1 debug, 1 error, 1 warning and 2 info(1 for log function, other one for info function). Here Debug() is seen as it is turned on by our application or by default. If we hide the Console Sidebar, we can see all the messages displayed in the Console except the debug message since it can be seen only in the verbose of the console, as:Conclusion: logging in AngularJS In this post, we started with logging in AngularJS. AngularJS comes with a service called $log for logging. $log is a simple wrapper around the console.log facilities. We understood the difference between $log.info, $log.warn, $log.error, $log.log and $log.debug. We learned how to extend $log through AngularJS application and even work with extended features of the same. We also saw how to switch off debugging in AngularJS logging. Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
10475
Logging in AngularJS Applications Made Simple

What comes to mind, when you think of a JavaScript... Read More

Introduction to Mongo DB

MongoDB, a highly scalable No-SQL database, is used for storing information in the form of JSON strings, where the structure of the table is not fixed (unlike in SQL database). So, the advantage here is that with the help of MongoDB, we can make quick changes in our entities without actually changing the database. MongoDB is available in multiple variants and what you choose would depend on the type of development you are looking for. You can download and install the relevant server as per your operating system from here.  If you are already a Mongo user then you may have had the chance to work with the huge number of operations that Mongo provides for storing and retrieving information in a database.If you want to brush up the same before starting on this article, refer to the basics of MongoDB here. In this article, we will learn about how we can use a MongoDB database with NodeJS.  But before do that, let’s delve a little into NodeJS. Getting started with NodeJS  So what is Node JS, and why do we use it? NodeJS is a backend JavaScript runtime environment that has become a favorite with developers and designers alike, due to the marvellous advantages it offers such as minimalism, speed, and compatibility with JavaScript. Not just individual programmers but world-class top tech companies around the world are using NodeJS as their backend tech stack because of the advantages it offers.   The beauty of NodeJs lies in the fact that it allows developers to write frontend abstractions with backend written in NodeJS. We will write our first NodeJS program here but before that, we have to install NodeJs, which is pretty straightforward. Installing NodeJs Plugin for MongoDB:Follow these steps to install Node JS  Install NPM (Node Package Manager).  The Node Package Manager) plugin is used to install various NodeJS plugins with a single command. Double-check that you have npm installed in your system by simply running this command in your terminal: $ npm -v[Text Wrapping Break]6.13.6  Install the Node from NodeJs Website >> NodeJS.   See the type of Operation system and download the version as per your platform compatibility.  Follow the installation guide as suggested by the installer.  Check the node version by running this command in your terminal  $ node -v[Text Wrapping Break]v8.11.4  If you have installed Node before NPM, you will probably need to update your NPM.   npm install npm@latest -g  Installing MongoDB Node.js Driver  The Mongo NodeJS driver allows us to interact with the MongoDB databases from NodeJs applications. To install MongoDB Node.js driver, run this command in your terminal.   npm install mongodb   To see the list of current drivers installed in the system, run the following command:  npm list mongodb  If you are stuck or have issues with installation of the drivers, then this official documentation is a good reference to go through.  Now that we are ready with both the database and NodeJS backend, let’s move ahead and create a simple NodeJs project. The aim of this project is to insert and retrieve information from the database. Using Node.JS to connect to MongoDB database   To do this, we will write a simple Node.js script which will connect to our database. And then we will perform an operation to list all the databases in our cluster.Cluster? What is a cluster?     A cluster is nothing but a set of nodes that carry the copies of your database. At a high level, you can say, your database is stored inside a cluster. To work on databases with Node, the easiest way is to use Atlas service which is MongoDB’s fully-managed database. If you are still unfamiliar with these terms, you can go through the complete documentation here.    Connecting MongoDB  Now that we have all our installations in place, let’s get started with connecting our database from NodeJs. Let’s Code! We will begin with Importing the Mongo Client as shown below: const {MongoClient} = require('mongodb');  To connect to the MongoDB database we have to import the MongoClient class from the MongoDB module, the instance of which can be used to connect to the cluster or for accessing the database from that cluster. Next step is to use a Main() function, where we can call other functions and can get connected to MongoDB cluster. const uri = "mongodb+srv://:@/test?retryWrites=true&w=majority";   Note: You need to update your password and username for the user. Now that we are ready with our URI, create an instance of MongoClient as below: const client = new MongoClient(URI);  Your instance is ready, so now you can use MongoClient to connect to the cluster by calling client.connect() as below:  await client.connect();  We have used the await keyword so as to ensure that it blocks any further execution until our operation is completed. And that’s it. We are ready to interact with our database. Let’s try it out by simply printing the list of all the databases in our cluster.  await listAllDatabases(client);  You can put any name to the above function. The next step is to finally put all the functions together and wrap them in a try/catch block in order to handle any errors. try   await client.connect();   await listAllDatabases(client);catch (e) {    console.error(e);}  And, close the connection as below:  finally { await client.close(); }  No, let’s put everything together and call our main function() as:  async function main(){ const uri = "mongodb+srv://:@/test?retryWrites=true&w=majority"; const client = new MongoClient(uri); try {// Connect to the MongoDB cluster await client.connect(); // Here make the DB calls or some operations await  listAllDatabases(client);  catch (e) {    console.error(e); } finally { await client.close(); }  Break]main().catch(console.error);  //To see if there are aby errorsLet’s use our function “listAllDatabases” to list all the databases in our cluster.  async function listAllDatabases(client){  databasesList = await client.db().admin().listAllDatabases(); console.log("Databases List Is:");[Text Wrapping Break]    databasesList.databases.forEach(db => console.log(` - ${db.name}`));};  If you can’t wait to see your output, then all that is left to do is to save it. Save your file as list.js.  Time to execute the NodeJs script. Let’s execute the script by running the following command in our terminal:  (Ensure that the server is running and up!) node list.js  The output should come as below:  Databases: - data_books - data_gates - data_houses - data_nodes- data_tables- admin - local  Now that we are running with the database, let’s see the different data types they are supported on.  Mongo DB data types Have you heard of BSON? BSON is a binary-encoded format of JSON. Documents in MongoDB are stored in the format of BSON. Here is a list of typically used data types supported by MongoDB: String − It is used to store the data. It should be UTF-8 valid. Integer − This data-type is used to store a numerical value. Depending on our server, Integer can be either of 32 bit or 64 bit. Boolean − To store a boolean (true/ false) value we use this type of data type. Double − Used for storing floating-point values. Arrays − This type of data-type is used for storing list or arrays. Timestamp - This type of data-type is used to check if an element has been modified or added. Min/ Max keys − We can use min or max data types for comparing the value against the lowest and highest BSON elements and vice-versa. Object − This data type stores embedded documents. (A document that contains another document in the form of the key-value pair) Null − This type of data-type is used by MongoDB to store a Null value. Symbol − It is not supported by a shell, but if it gets a symbol from the database, it is converted into a string. So it’s quite identical to a string data type. Regular expression − These MongoDB data types stores regular expressions in MongoDB. It maps directly to JavaScript Regular Expression. Date −  This type of data-type is used to store the date or time. We can also use our date or time by simply creating an object of Date and passing elements like day, month, year into it. Object ID − Mongo uses this type of datatype to store the document’s ID. Binary data − Typically used to store binary data. Mongo DB and Collections  A database can have multiple collections. A collection is a table that contains all your documents. We can create a collection as follows:  const collection = db.createCollection(name, options), or  const collection = db.collection(‘books’);     where, name is the connection name which can be anything, The option is a configuration document used for specifying the collection and is optional. We can list the following options while creating a collection: capped, autoIndexId, max, and size. createCollection() is an inbuilt method in MongoDB, which is used to create a new collection in database as shown above. Note: In MongoDB, a collection is never created until it gets some content!  db.collection('check', {strict:true}, function(err, collection) {});    So, this code will never create a collection until and unless you specify and insert it in the document.  ConclusionToday we learnt the basics of MongoDB, and how and why MongoDB is compatible with NodeJS. We also looked at how we can connect to our MongoDB database from NodeJS script, and found a cool demo of listing out the names of all the databases in our cluster. There are many activities that we can do with NodeJS in our database which involves the basic CRUD operations like insert, update, remove, or making a query in our collection.  And if you get stuck, see the official documentation of all of them here. It has plenty of features that make our job easier.  Happy Learning! :) 
10473
Introduction to Mongo DB

MongoDB, a highly scalable No-SQL database, is use... Read More