top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Overview about ngRoute and UIRouter ?

0 votes
300 views

What is Router?
Router is playing important role in Single Page Application (SPA). It is getting & applying the Partials/Views/Templates into corresponding places.

ngRoute

  • ngRoute is an angular core module which is good for basic scenarios.
  • This is URL routing approach

Uiview

  • UIRouter is a contributed module which is overcome the problems of ngRoute. 
  • This is State Based Approach


Ui-Router is designed to handle large apps,using complex views, while ng-route is well suited for basic scenarios.

More from UI-Router:

  • It handles nested views and multiple named views
  • It allows for you to have strong type linking between states based on state names,
  • It's easier to map and access different information about different states and pass information between states via $stateParams.

Video Link

posted Oct 24, 2016 by Parampreet Kaur

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Interceptors define custom transformations for HTTP requests and responses at the application level. In other words, interceptors define general rules for how your application processes HTTP requests and responses.

An interceptor is simply a factory() service that returns an object with 4 properties that map to functions:

  • request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
  • requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
  • response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.
  • responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.


We activate an interceptor service by pushing that service into the $httpProvider.interceptors array in the config block of our application.
A session token can be added for all outgoing HTTP requests by adding it to the config.headers object in a request interceptor.
We can intercept HTTP response errors and handle specific errors by checking the response.status code.
$rootScope has limited utility when it comes to direct interaction, but it works well as an event bus as seen in the case of keeping our MainCtrl synchronized.

 

Example Code:

m.config(function($httpProvider) {
  $httpProvider.interceptors.push(function($q, $injector, userService) {
    return {
      request: function(request) {
        request.headers.authorization =
          userService.getAuthorization();
        return request;
      },
      // This is the responseError interceptor
      responseError: function(rejection) {
        if (rejection.status === 401) {
          // Return a new promise
          return userService.authenticate().then(function() {
            return $injector.get('$http')(rejection.config);
          });
        }

        /* If not a 401, do nothing with this error.
         * This is necessary to make a `responseError`
         * interceptor a no-op. */
        return $q.reject(rejection);
      }
    };
  });
});

 

Video for HTTP Interceptors

https://www.youtube.com/watch?v=K6W0kf6o_Zk​

READ MORE

Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object.

A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

A new instance of deferred is constructed by calling $q.defer().

Methods:

  • Resolve(value)
  • Reject(reason)
  • Notify(notify)

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.

Methods:

  • then()
  • catch()
  • finally()


$q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.

Example Code:

var deferred = $q.defer();
var promise = deferred.promise;
 
promise.then(function success(data) {
  console.log('Success!', data);
}, function error(msg) {
  console.error('Failure!', msg);
});
 
deferred.reject('We failed :(');

Video about Angular Services

https://www.youtube.com/watch?v=cdG_T6ufcbE​

READ MORE

It is important to understand the different prompts you can find when configuring a router so you can know where you are at any time within configuration mode. In this lab, the prompts that are used on a Cisco router will be demonstrated. Always check your prompts before making any changes to a routers configuration.

1- To configure a device from the CLI, you can make global changes to the router by typing configure terminal (config t for short), which puts you in global configuration mode and changes what is known as the running-config. You can type config from the privileged mode prompt and then just press enter to take the default of terminal.

Router#config

Configuring from terminal, memory, or network [terminal]?enter
Enter configuration commands, one per line.  End with CTRL/Z.

Router(config)#
At this point you make changes that affect the router as a whole, hence the term global configuration mode. Notice the prompt is now Router(config)#.

2-   To make changes to an interface, you use the interface command from global configuration mode.

Router(config)#interface ?
Async =============> Async interface
BRI===============> ISDN Basic Rate Interface
BVI ===============>Bridge-Group Virtual Interface
CTunnel ===========>CTunnel interface
Dialer =============> Dialer interface
FastEthernet ========>FastEthernet IEEE 802.3
Group-Async =======>Async Group interface
Lex ===============>Lex interface
Loopback ==========>Loopback interface
MFR ===============>Multilink Frame Relay bundle interface
Multilink =========>Multilink-group interface
Null ==============>Null interface
Tunnel ============> Tunnel interface
Vif ===============>PGM Multicast Host interface
Virtual-Template ==> Virtual Template interface
Virtual-TokenRing ==>Virtual TokenRing
range ============> interface range command

Router(config)#interface fastethernet 0/0
Router(config-if)#

Notice the prompt changed to Router(config-if)# to tell you that you are in interface configuration.

3- Sub interfaces allow you to create virtual interfaces within the router. The prompt then changes to.

Router(config-subif)#.

Router(config-if)#int f0/0.?
<0-4294967295> FastEthernet interface number
Router(config-if)#int f0/0.1
Router(config-subif)#

Type exit to go back to global configuration mode.

Router(config-subif)#exit
Router(config)#

4- To configure user mode passwords, use the line command. The prompt then becomes Router(config-line)#.

Router#config t
Enter configuration commands, one per line. End with CTRL/Z.
Router(config)#line ?

<0-70> First Line number
aux Auxiliary line
console Primary terminal line
tty Terminal controller
vty Virtual terminal
x/y Slot/Port for Modems

Router(config)#line console 0
Router(config-line)#

The line console 0 command is known as a major, or global, command, and any command typed from the (config-line) prompt is known as a subcommand.

5-  Type exit to go back to global configuration mode.

Router(config-subif)#exit
Router(config)#

6-  To configure routing protocols like RIP and IGRP, use the prompt (config-router)#. 

Router(config)#router rip
Router(config-router)#

It is not important that you understand what each of these commands does at this time. These will all be explained later in great detail in the standard and extended labs. What you need to understand is the different prompts available.

7. Type control+z to go back to global configuration mode.

Router(config-router)#^z
Router#

READ MORE

What is Angular App Exception Handling?

The AngularJS $exceptionHandler service allows you to catch and handle unanticipated JavaScript errors in a meaningful way.

Example:
app.factory('$exceptionHandler',function($log,ErrorService) {
    return function(exception,cause) {
        if(console) {
        }
        
    }
    ErrorService.send(exception,cause);
});

Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console. In unit tests, if angular-mocks.js is loaded, this service is overridden by mock $exceptionHandler which aids in testing.

$exceptionHandler is very useful for sending errors to third party error logging services or helpdesk applications. Errors trapped inside of event callbacks are not propagated to this handler, but can manually be relayed to this handler by calling $exceptionHandler(e) from within a try catch block.

Video Tutorial for handling Exception Handling

https://www.youtube.com/watch?v=9xdIvUD2Jug

READ MORE

Providers
A provider is the most sophisticated method of all the providers. It allows you to have a complex creation function and configuration options. A provider is actually a configurable factory.

var app = angular.module('myModule',[]);

app.provider("myProvider", function() {
    this.value = "My Value";

    this.setValue = function(newValue) {
        this.value = newValue;
    };

    this.$get = function() {
        return this.value;
    };
});

app.config(function(myProviderProvider) { // ADDED config section
    // Note the extra "Provider" suffix
    myProviderProvider.setValue("New Value");
});

Services

A service is an injectable constructor. If you want you can specify the dependencies that you need in the function. A service is a singleton and will only be created once by AngularJS. 

app.service("myProvider", function() { 
    this.getValue = function() {
        return "My Value";
    };
});

 

Factories
A factory is an injectable function. A factory is a lot like a service in the sense that it is a singleton and dependencies can be specified in the function. The difference between a factory and a service is that a factory injects a plain function so AngularJS will call the function and a service injects a constructor.

app.factory("myProvider", function() { 
    return "My Value";
});


Value
A value is nothing more than a simple injectable value. The value can be a string, number but also a function.

var app = angular.module('myModule',[]);

app.value("Value1", "First Value");
app.value("Value2", "Second  Value");


Constants

A constant can be injected everywhere. The value of a constant can never be changed.


var app = angular.module('myModule',[]);


app.constant("Constant1", "First Constant Value");
app.constant("Constant2", "Second Constant Value");

Video Tutorial

https://www.youtube.com/watch?v=jpT8vn5AhpY

READ MORE

How to use Angular.js Expressions,Numbers,Strings,Objects and Arrays

In Angular.js all Numbers,Strings,Object and Arrays are exactly similar to java script.

Angular.js Expressions

AngularJS expressions are written inside double braces: {{ expression }}.

AngularJS expressions binds data to HTML the same way as the ng-bind directive.

AngularJS will "output" data exactly where the expression is written.

AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.

In each section i entered examples for both {{ expression }} and ng-bing.

AngularJS Numbers

AngularJS numbers are like JavaScript numbers:

Example Using expression:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

Total in dollar : 5

Same example using ng-bind:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

OutPut:

Total in dollar:5

AngularJS Strings

AngularJS strings are like JavaScript strings:

Example Using expression:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-init="firstName='manish';lastName='tiwari'">

<p>The full name is: {{ firstName + " " + lastName }}</p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output :

The full name is: manish tiwari

Same example using ng-bind:

<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-init="firstName='manish';lastName='tiwari'">

<p>The full name is: <span ng-bind="firstName + ' ' + lastName"></span></p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output :

The full name is: manish tiwari

AngularJS Objects

AngularJS objects are like JavaScript objects:

<!DOCTYPE html>
<html>

<body>

<div ng-app="" ng-init="person={firstName:'manish',lastName:'tiwari'}">

<p>The name is {{ person.lastName }}</p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

The name is tiwari

Same example using ng-bind:

<!DOCTYPE html>
<html>

<body>

<div ng-app="" ng-init="person={firstName:'manish',lastName:'tiwari'}">

<p>The name is <span ng-bind="person.lastName"></span></p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

The name is tiwari

AngularJS Arrays

AngularJS arrays are like JavaScript arrays:

Example Using Expressions:

<!DOCTYPE html>
<html>

<body>

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is {{ points[2] }}</p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

The third result is 19

Same example using ng-bind:

<!DOCTYPE html>
<html>

<body>

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is <span ng-bind="points[2]"></span></p>

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Output:

The third result is 19
READ MORE

How to Start Angular.js & How to Extend html in Angular.js?

AngularJS is a JavaScript framework. It can be added to an HTML page with a tag.

AngularJS is a JavaScript framework. It is a library written in JavaScript.

AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

How to Start Angular.js?

When writing an AngularJS app, we write the behavior and interaction together alongside the presentation.

Writing this way can be confusing at first, especially if you have experience with other frameworks where the two are generally separate. Once you get the hang of it, it’ll become second nature.

Let’s look at the simplest app you can build with AngularJS:

Simple Example For Angular.JS

<!doctype html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  </head>
  <body>
    <div>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <h1>Hello, {{ yourName }}!</h1>
    </div>
  </body>
</html>

Output For The Above Code

enter image description here

In above text box what ever you type it will bind automatically in the header tag <h1></h1>

As you can see, you get bi-directional data binding without any work.

Bi-directional data binding means that if you change data on the back end, your changes will show up in your view automagically (actually, there’s no magic involved; we’ll get into how this works soon).

Similarly, if you change data in your view (e.g., by typing into a text box), it will automagically update your model.

So what did we do in our app?

ng-app
ng-model
= yourName
{{ yourName }}

First, we used our most important (and most easily forgotten) term: the ng-app attribute on the tag. Without this tag, the AngularJS process does not start.

Second, we told AngularJS that we want to set up bi-directional data binding on the yourName model on the page.

Third, we told AngularJS to display the data yourName in the directive template called {{ yourName }}.

How AngularJS Extends HTML ?

AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

The ng-model directive binds element values (like the value of an input field) to the application.

The ng-bind directive binds application data to the HTML view.

Example Code:

<!DOCTYPE html>
<html>
<body>

<!-- Angular Directive Starts -->
<div ng-app="">

<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p> <!-- Here ng-model binds the value of Input Filed -->
<p ng-bind="name"></p> <!-- Here binds application variable name to the innerHTML of a paragraph. -->

</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

</body>
</html>

Above Code Explanation

AngularJS starts automatically when the web page has loaded.

The ng-app directive tells AngularJS that the

element is the "owner" of an AngularJS application.

The ng-model directive binds the value of the input field to the application variable name.

The ng-bind directive binds application variable name to the innerHTML of a paragraph.

Note:

Suppose,If you remove the ng-app directive, HTML will display the expression as it is, without solving it.

READ MORE
...