Takeaways from this article In this post, we will understand how and why Angular JS Routing is better in comparison to traditional frameworks, and how this routing can be achieved seamlessly with the help of Angular UI Router.  We will understand the usage and importance of states, and how they help in navigating easily through the application. We will see a sample with a state definition and its usage, and how it helps in resolving issues and making the page user-friendly.  Introduction  Angular JS is a popular application framework that is used for front-end development. It works great when creating single page applications. It is written in JavaScript and is being maintained by tech-giant Google. It is used to interpret the HTML attributes in a webpage in the form of directives and bind the respective input and output components of the model, that are represented in the form of JavaScript variables. Angular UI Routing helps navigate between views and pages seamlessly without getting messy, and in a user-friendly manner.  Note: It is assumed that the reader is aware of technologies like HTML, CSS, JavaScript and Angular JS. Native Angular Routing doesn’t have the following facilities: No nested views No named views Data can’t be passed around between two views The syntax of the route should be literally remembered to navigate the page The URL string has to be manually changed via the code base when a URL is changed. When a URL changes, all the links associated with that URL have to be changed and updated to point to the new location.  In order to minimize the above disadvantages, Angular UI Router is used.  Introduction to Angular JS Routing Angular JS Routing is an advanced technique that helps in routing, that has a declarative approach in navigating through the pages of a website. In a webpage, when a link that points to a different page is created, the URL has to be explicitly defined. This path has to be literally memorized and if it is changed, then the URL would have to be changed in all places where it was previously referenced. This is when Angular JS Routing comes into play.  Angular UI Router is a module in Angular JS that helps in the process of routing in Angular JS applications. The Router facilitates in the creation as well as usage of such routes in applications. The Router consists of a method called ‘stateProvider’ which helps in the creation of ‘states’, also known as ‘routes’.  The method ‘stateProvider’ takes the name of the state and the configurations of the state as its parameters. It looks like below:$stateProvider.state(stateName, stateConfig)The above function creates a state in the application. The parameter ‘stateName’ is a string value that is used to create a parent or a child state. To create a child state, the parent state is referenced with the help of the dot operator. The ‘stateConfig’ parameter is an object that can take many properties, such as: template: It is a string in the form of HTML content or a function that returns a HTML string as the output. templateUrl: It is a string that is a URL path to a specific template file or a function that returns a URL path string as the output. templateProvider: It is a function that returns the HTML content as a string output. Note: The ‘stateConfig’ parameter can take only one property at a time per state or per view with respect to the application. The states in an application help the user in navigating or reconstituting to the situation that occurs within the application’s working. Note: The latest version of UI Router can be downloaded from the GitHub repository. Below are three examples when ‘stateConfig’ has different properties: With ‘template’ as a property:$stateProvider.state(‘stateName’,   {      url: ‘url for the specific state’,     template: ‘html content’,     controller: "name of controller for specific state" });With ‘templateUrl’ as a property:$stateProvider.state('stateName', { url: ‘url for the specific state’, templateProvider: ‘function name’, controller: "name of controller for specific state" });Introduction to Angular JS Router It is one of the modules in Angular JS that helps in creating routes for applications that use Angular JS. Applications are encompassed in a shell, and this shell behaves like a placeholder for the dynamic content that would be generated later. The UI Router is a routing framework that changes the views of the application based on not just the URL, but the state of the application as well. It helps in bridging the gap between the traditional frameworks, by allowing nested views, named views, passage of data between two different views, and so on. Routes are an integral part of Single Page Applications that are preferably created using Angular JS. With the help of Angular UI Router, these routes can be created with ease and can be used with ease in Angular JS. The ‘state’ facility gives the flexibility to encapsulate the location of the URL state name, special data for view, generate a view, or even locate a view. Angular UI Router consists of a ‘stateProvider’ method that can be used to create a route or a state in an application. The ‘stateProvider’ function takes the name of the state and the configurations of the state as its parameter. In addition to this, Angular UI Router also helps resolve dependencies before initializing the controller. It provides utility filters, declarative transitions, state change events, and so on. What is the difference between State and URL Routes? State Route The views and routes of the Angular JS page will not be bound with just the URL of the site. The specific parts of the site can be changed with the help of UI Routing even if the URL has been kept the same. All the states, routing, and viewing capabilities of the page are handled at a single one-stop place- the ‘.config()’. URL Route URL route is a little different. It is usually implemented using ‘ngroute’, and it needs the implementation of methods such as ‘nginclude’. If the number of methods increases, the situation could get complicated and handling of these methods gets difficult.Stepwise routing with detailed explanation The node.js and npm have to be installed prior to working with the below steps. For this purpose, the http-server node module has to be run and installed which will help in hosting the demo application that we would create. It can be installed with the help of the below command: npm install http-server –gA hierarchical directory structure needs to be created. A sample has been shown below:Demo_App --app.js --index.html --nav.htmlThe ‘nav.html’ file needs to have the content as mentioned below: The nav bar title The contents of the file The two different actions that would be created will also be mentioned here (The home page and the log in.) The index.html file will have the required dependencies along with nav.html file. The nav.html file will be included in the body tag of the index.html page. The dependencies will be included with the help of ‘CDN’ in the head tag. A separate body tag will be used to define the ui-view div. The ui-view is a section where the information about various routes content and how they would be rendered is present. The ui-view is a directive that is present inside the ui.router module. The ui-view directive tells the ‘$state’ about the positioning of the template properties (or other property) It would look like below (sample): <script src="angular.name.js"> </script> <script src = "https://unpkg.com/@uirouter/angularjs@1.0.7/release/angular-ui-router.min.js"> </script>An app.js file can be created, which is an application file that contains the route information and the actions that need to be performed with the help of the controller in the application framework. Below is a sample app.js file:var app = angular.module('Demo_App', [ "ui.router" ]);   app.config(function($stateProvider,$locationProvider,                                   $urlRouterProvider) {$stateProvider.state('home_page',   {               url : '/home',               template : "<h1>Home page</h1>",               controller : "hmeCtrl"         })           .state('login_page',   {               url : '/login',               template : "<h1>Login page</h1>",               controller : "lgnCtrl"         })       $urlRouterProvider.otherwise("/home"); }); app.controller('mainCtrl', function() {}); app.controller('hmeCtrl', function() {}); app.controller('lgnCtrl', function() {});The first line of the sample code declares the name of the application module and injects a ui.router module dependency into it. Next, the route configurations are defined inside the app.config and the dependency injections are set up. The routes for the required attributes are set up with the help of the ‘stateProvider’ function and mentioning the required parameters. Once the home page and the login have been set up, a condition is set up where the page would be redirected back to the home page if any of the routes don’t match the url name. This is done with the help of the ‘otherwise’ function. Empty states are created for the controllers. This is done since it is a sample and no operation is being performed inside these states. The above sample application can be run in the browser after the http-serve node module has been installed (as mentioned in the first step of this explanation). Next step is to navigate to the ‘routingDemo’ folder and execute the below mentioned command:http-serverThis command helps in hosting the demonstration application on the default port that is 8080. This can be accessed with the help of the below mentioned link:localhost:8080/When the application is accessed via a browser, it will be a web application with two routes, namely: Home Login Conclusion In this post, we understood the prominence of Angular JS Routing and Router, and how they are different from the traditional approaches. They help bridge a gap between the features that traditional approaches implement, thereby increasing the ability of web pages to work and perform in a better, more user-friendly manner.Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article. # Easier Angular JS Routing With Angular UI Router 7K • by Amit Diwan • 25th Sep, 2020 • Last updated on 05th Oct, 2020 • 6 mins read Takeaways from this article • In this post, we will understand how and why Angular JS Routing is better in comparison to traditional frameworks, and how this routing can be achieved seamlessly with the help of Angular UI Router. • We will understand the usage and importance of states, and how they help in navigating easily through the application. • We will see a sample with a state definition and its usage, and how it helps in resolving issues and making the page user-friendly. ## Introduction Angular JS is a popular application framework that is used for front-end development. It works great when creating single page applications. It is written in JavaScript and is being maintained by tech-giant Google. It is used to interpret the HTML attributes in a webpage in the form of directives and bind the respective input and output components of the model, that are represented in the form of JavaScript variables. Angular UI Routing helps navigate between views and pages seamlessly without getting messy, and in a user-friendly manner. Note: It is assumed that the reader is aware of technologies like HTML, CSS, JavaScript and Angular JS. Native Angular Routing doesn’t have the following facilities: • No nested views • No named views • Data can’t be passed around between two views • The syntax of the route should be literally remembered to navigate the page • The URL string has to be manually changed via the code base when a URL is changed. When a URL changes, all the links associated with that URL have to be changed and updated to point to the new location. In order to minimize the above disadvantages, Angular UI Router is used. ## Introduction to Angular JS Routing Angular JS Routing is an advanced technique that helps in routing, that has a declarative approach in navigating through the pages of a website. In a webpage, when a link that points to a different page is created, the URL has to be explicitly defined. This path has to be literally memorized and if it is changed, then the URL would have to be changed in all places where it was previously referenced. This is when Angular JS Routing comes into play. Angular UI Router is a module in Angular JS that helps in the process of routing in Angular JS applications. The Router facilitates in the creation as well as usage of such routes in applications. The Router consists of a method called ‘stateProvider’ which helps in the creation of ‘states’, also known as ‘routes’. The method ‘stateProvider’ takes the name of the state and the configurations of the state as its parameters. It looks like below: $stateProvider.state(stateName, stateConfig)

The above function creates a state in the application. The parameter ‘stateName’ is a string value that is used to create a parent or a child state. To create a child state, the parent state is referenced with the help of the dot operator.

The ‘stateConfig parameter is an object that can take many properties, such as:

• templateIt is a string in the form of HTML content or a function that returns a HTML string as the output.
• templateUrl: It is a string that is a URL path to a specific template file or a function that returns a URL path string as the output.
• templateProvider: It is a function that returns the HTML content as a string output.

Note: The ‘stateConfig’ parameter can take only one property at a time per state or per view with respect to the application.

The states in an application help the user in navigating or reconstituting to the situation that occurs within the application’s working.

Below are three examples when ‘stateConfig’ has different properties:

With ‘template’ as a property:

$stateProvider.state(‘stateName’, { url: ‘url for the specific state’, template: ‘html content’, controller: "name of controller for specific state" }); With ‘templateUrl’ as a property: $stateProvider.state('stateName',
{
url: ‘url for the specific state’,
templateProvider: ‘function name’,
controller: "name of controller for specific state"
});

## Introduction to Angular JS Router

• It is one of the modules in Angular JS that helps in creating routes for applications that use Angular JS.
• Applications are encompassed in a shell, and this shell behaves like a placeholder for the dynamic content that would be generated later.
• The UI Router is a routing framework that changes the views of the application based on not just the URL, but the state of the application as well.
• It helps in bridging the gap between the traditional frameworks, by allowing nested views, named views, passage of data between two different views, and so on.
• Routes are an integral part of Single Page Applications that are preferably created using Angular JS.
• With the help of Angular UI Router, these routes can be created with ease and can be used with ease in Angular JS.
• The ‘state’ facility gives the flexibility to encapsulate the location of the URL state name, special data for view, generate a view, or even locate a view.
• Angular UI Router consists of a ‘stateProvider’ method that can be used to create a route or a state in an application.
• The stateProvider function takes the name of the state and the configurations of the state as its parameter.
• In addition to this, Angular UI Router also helps resolve dependencies before initializing the controller.
• It provides utility filters, declarative transitions, state change events, and so on.

## What is the difference between State and URL Routes?

### State Route

The views and routes of the Angular JS page will not be bound with just the URL of the site. The specific parts of the site can be changed with the help of UI Routing even if the URL has been kept the same. All the states, routing, and viewing capabilities of the page are handled at a single one-stop place- the ‘.config()’.

### URL Route

URL route is a little different. It is usually implemented using ‘ngroute’, and it needs the implementation of methods such as ‘nginclude’. If the number of methods increases, the situation could get complicated and handling of these methods gets difficult.

### Stepwise routing with detailed explanation

• The node.js and npm have to be installed prior to working with the below steps.
• For this purpose, the http-server node module has to be run and installed which will help in hosting the demo application that we would create.
• It can be installed with the help of the below command:
npm install http-server –g
• A hierarchical directory structure needs to be created. A sample has been shown below:
Demo_App
--app.js
--index.html
--nav.html
• The ‘nav.html’ file needs to have the content as mentioned below:
• The nav bar title
• The contents of the file
• The index.html file will have the required dependencies along with nav.html file.
• The nav.html file will be included in the body tag of the index.html page.
• The dependencies will be included with the help of ‘CDN’ in the head tag. A separate body tag will be used to define the ui-view div.
• The ui-view is a section where the information about various routes content and how they would be rendered is present
• The ui-view is a directive that is present inside the ui.router module.
• The ui-view directive tells the ‘$state’ about the positioning of the template properties (or other property) It would look like below (sample): <script src="angular.name.js"> </script> <script src = "https://unpkg.com/@uirouter/angularjs@1.0.7/release/angular-ui-router.min.js"> </script> • An app.js file can be created, which is an application file that contains the route information and the actions that need to be performed with the help of the controller in the application framework. Below is a sample app.js file: var app = angular.module('Demo_App', [ "ui.router" ]); app.config(function($stateProvider, $locationProvider,$urlRouterProvider)
{
$stateProvider.state('home_page', { url : '/home', template : "<h1>Home page</h1>", controller : "hmeCtrl" }) .state('login_page', { url : '/login', template : "<h1>Login page</h1>", controller : "lgnCtrl" })$urlRouterProvider.otherwise("/home");
});
app.controller('mainCtrl', function() {});
app.controller('hmeCtrl', function() {});
app.controller('lgnCtrl', function() {});
1. The first line of the sample code declares the name of the application module and injects a ui.router module dependency into it.
2. Next, the route configurations are defined inside the app.config and the dependency injections are set up.
3. The routes for the required attributes are set up with the help of the ‘stateProvider’ function and mentioning the required parameters.
4. Once the home page and the login have been set up, a condition is set up where the page would be redirected back to the home page if any of the routes don’t match the url name. This is done with the help of the ‘otherwise’ function.
5. Empty states are created for the controllers. This is done since it is a sample and no operation is being performed inside these states.
• The above sample application can be run in the browser after the http-serve node module has been installed (as mentioned in the first step of this explanation).
• Next step is to navigate to the ‘routingDemo’ folder and execute the below mentioned command:
http-server
• This command helps in hosting the demonstration application on the default port that is 8080. This can be accessed with the help of the below mentioned link:
localhost:8080/
• When the application is accessed via a browser, it will be a web application with two routes, namely:
• Home

## Conclusion

In this post, we understood the prominence of Angular JS Routing and Router, and how they are different from the traditional approaches. They help bridge a gap between the features that traditional approaches implement, thereby increasing the ability of web pages to work and perform in a better, more user-friendly manner.

### Amit Diwan

Author

Amit Diwan is an E-Learning Entrepreneur, who has taught more than a million professionals with Text & Video Courses on the following technologies: Data Science, AI, ML, C#, Java, Python, Android, WordPress, Drupal, Magento, Bootstrap 4, etc.

## Join the Discussion

SPECIAL OFFER Upto 20% off on all courses
Enrol Now

## 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.
6559
What Is Dependency Injection in AngularJS

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

## 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  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: Expense on Books : {{cost * quantity}} Rs Expressions Using strings. Example: Hello {{student.firstname + " " + student.lastname}}! Expressions Using object. Example: Roll No: {{student.rollno}} Expressions Using array. Example: Marks(Math): {{marks[3]}} 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:               My first expression: {{ 5 + 5 }} 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:       Number Expression of AngularJs      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {$scope.expr1 = 10;  $scope.expr2 = 20 }); Number Expression The Result of Addition is : {{expr1 + expr2}} 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: Number Expression of AngularJs The Result of Addition is : 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: String Expressions of AngularJS 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); }); String Expression The Result of Concatenation of {{expr1}} and {{expr2}} is : {{expr1 + expr2}} The Result of angular.isString() for parameter {{expr1}} is : {{isString1}} The Result of angular.isString() for parameter {{expr3}} is : {{isString2}} 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:       String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {$scope.AngularTraining = {  Trainer: 'Monica',  noOfStd: 10,  noOfHours: 24  };   });                Pure JSON object contains key value pairs as Object Expression        The AngularTraining Object is:    AngularTraining.Trainer: {{ AngularTraining.Trainer}}     AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}     AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}             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:       String Expressions of AngularJS                Pure JSON object contains key value pairs as Object Expression        The AngularTraining Object is:    AngularTraining.Trainer: {{ AngularTraining.Trainer}}     AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}     AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}             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:       String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {$scope.name = "Monica";  $scope.leave = [1, 2, 0]; }); Array Expression The Leave Report for the first quarter for Employee: {{name}} is: January: {{ leave[0] }} February: {{ leave[1] }} March: {{ leave[2] }} Total Leave for the first Quarter is: {{ leave[0] + leave[1] + leave[2] }} 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: String Expressions of AngularJS Array Expression The Leave Report for the first quarter for Employee: {{name}} is: January: {{ leave[0] }} February: {{ leave[1] }} March: {{ leave[2] }} Total Leave for the first Quarter is: {{ leave[0] + leave[1] + leave[2] }} 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: AngularJS Expressions Expression Hello {{student.firstname + " " + student.lastname}}! Expense on Books : {{cost * quantity}} Rs Roll No: {{student.rollno}} Marks(Math): {{marks[3]}} 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 {{ textBinding }}. 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.
9157
Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-ba... 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.
10474
Logging in AngularJS Applications Made Simple

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