​What were some features introduced in the different versions of Angular (2, 4, 5and 6)?

Requirement: Expert Angular knowledge, Component-based architectureAnswer:

Angular 2:

  • Complete rewrite of the Angular framework
  • Component-based rather than controllers/view/$scope. This allows more code to be reused,easier communication between components and easier testing
  • Much faster
  • Support for mobile devices
  • More language choices such as TypeScript

Angular 4:

  • An update to Angular 2, not a complete rewrite. Updating from Angular 2 to 4 just requiresupdating the core libraries
  • Improvements to Ahead-of-time (AOT) generated code
  • Support for new versions of TypeScript
  • Animation packages are removed from the core package
  • Else block

Angular 5:

  • Focused on making Angular smaller and faster to use
  • Http is depreciated and HttpClient API client is now recommended for all apps
  • Supports TypeScript 2.3
  • Introduction of a build optimizer
  • Angular Universal State Transfer API
  • Improvements to the Angular Compiler
  • Router Lifecycle Events
  • Better cross-browser standardization

Angular 6:

  • Better service worker support
  • Better URL serialization
  • Ivy rendering engine
  • ng update and ng add
  • <template> element completely removed
  • Angular Elements/Custom Elements
  • Form validation changes
  • Schematics
  • What is Angular Framework?

Angular is a TypeScript-based open-source front-end platform that makes it easy to build applications with in web/mobile/desktop. The major features of this framework such as declarative templates, dependency injection, end to end tooling, and many more other features are used to ease the development.

  • What is the difference between AngularJS and Angular?

Angular is a completely revived component-based framework in which an application is a tree of individual components.

Some of the major difference in tabular form

AngularJS Angular
It is based on MVC architecture This is based on Service/Controller
This uses use JavaScript to build the application Introduced the typescript to write the application
Based on controllers concept This is a component based UI approach
Not a mobile friendly framework Developed considering mobile platform
Difficulty in SEO friendly application development Ease to create SEO friendly applications
  • What is TypeScript?

TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes, async/await, and many other features, and compiles to plain JavaScript. Angular built entirely in TypeScript and used as a primary language. You can install it globally as

npm install -g typescript

Let’s see a simple example of TypeScript usage,

function greeter(person: string) {

return “Hello, ” + person;

}

 

let user = “Sudheer”;

 

document.body.innerHTML = greeter(user);

The greeter method allows only string type as argument.

  • Write a pictorial diagram of Angular architecture?

The main building blocks of an Angular application is shown in the below diagram

  • What are the key components of Angular?

Angular has the below key components,

  1. Component: These are the basic building blocks of angular application to control HTML views.
  2. Modules: An angular module is set of angular basic building blocks like component, directives, services etc. An application is divided into logical pieces and each piece of code is called as “module” which perform a single task.
  3. Templates: This represent the views of an Angular application.
  4. Services: It is used to create components which can be shared across the entire application.
  5. Metadata: This can be used to add more data to an Angular class.
  • What are directives?

Directives add behaviour to an existing DOM element or an existing component instance.

import { Directive, ElementRef, Input } from ‘@angular/core’;

 

@Directive({ selector: ‘[myHighlight]’ })

export class HighlightDirective {

constructor(el: ElementRef) {

el.nativeElement.style.backgroundColor = ‘yellow’;

}

}

Now this directive extends HTML element behavior with a yellow background as below

<p myHighlight>Highlight me!</p>

  • What are components?

Components are the most basic UI building block of an Angular app which formed a tree of Angular components. These components are subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template. Let’s see a simple example of Angular component

import { Component } from ‘@angular/core’;

 

@Component ({

selector: ‘my-app’,

template: ` <div>

<h1>{{title}}</h1>

<div>Learn Angular6 with examples</div>

</div> `,

})

 

export class AppComponent {

title: string = ‘Welcome to Angular world’;

}

  • What are the differences between Component and Directive?

In a short note, A component(@component) is a directive-with-a-template.

Some of the major differences are mentioned in a tabular form

Component Directive
To register a component we use @Component meta-data annotation To register directives we use @Directive meta-data annotation
Components are typically used to create UI widgets Directive is used to add behavior to an existing DOM element
Component is used to break up the application into smaller components Directive is use to design re-usable components
Only one component can be present per DOM element Many directives can be used per DOM element
@View decorator or templateurl/template are mandatory Directive doesn’t use View
  • What is a template?

A template is a HTML view where you can display data by binding controls to properties of an Angular component. You can store your component’s template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator’s templateUrl property. Using inline template with template syntax,

import { Component } from ‘@angular/core’;

 

@Component ({

selector: ‘my-app’,

template: ‘

<div>

<h1>{{title}}</h1>

<div>Learn Angular</div>

</div>

})

 

export class AppComponent {

title: string = ‘Hello World’;

}

Using separate template file such as app.component.html

import { Component } from ‘@angular/core’;

 

@Component ({

selector: ‘my-app’,

templateUrl: ‘app/app.component.html’

})

 

export class AppComponent {

title: string = ‘Hello World’;

}

  • What is a module?

Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application. Lets take an example of app.module.ts root module declared with @NgModule decorator as below,

import { NgModule }      from ‘@angular/core’;

import { BrowserModule } from ‘@angular/platform-browser’;

import { AppComponent }  from ‘./app.component’;

 

@NgModule ({

imports:      [ BrowserModule ],

declarations: [ AppComponent ],

bootstrap:    [ AppComponent ]

})

export class AppModule { }

The NgModule decorator has three options

  1. The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application
  2. The declarations option is used to define components in the respective module
  3. The bootstrap option tells Angular which Component to bootstrap in the application
  • What are lifecycle hooks available?

Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The representation of lifecycle in pictorial representation as follows,

The description of each lifecycle method is as below,

  1. ngOnChanges: When the value of a data bound property changes, then this method is called.
  2. ngOnInit: This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
  3. ngDoCheck: This is for the detection and to act on changes that Angular can’t or won’t detect on its own.
  4. ngAfterContentInit: This is called in response after Angular projects external content into the component’s view.
  5. ngAfterContentChecked: This is called in response after Angular checks the content projected into the component.
  6. ngAfterViewInit: This is called in response after Angular initializes the component’s views and child views.
  7. ngAfterViewChecked: This is called in response after Angular checks the component’s views and child views.
  8. ngOnDestroy: This is the cleanup phase just before Angular destroys the directive/component.
  • What is a data binding?

Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding(divided as 3 categories) which differ in the way the data is flowing.

  1. From the Component to the DOM: Interpolation: {{ value }}: Adds the value of a property from the component

<li>Name: {{ user.name }}</li>

<li>Address: {{ user.address }}</li>

Property binding: [property]=”value”: The value is passed from the component to the specified property or simple HTML attribute

<input type=”email” [value]=”user.email”>

  1. From the DOM to the Component: Event binding: (event)=”function”: When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component

<button (click)=”logout()”></button>

  1. Two-way binding: Two-way data binding: [(ngModel)]=”value”: Two-way data binding allows to have the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync

<input type=”email” [(ngModel)]=”user.email”>

  • What is metadata?

Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators

  1. Class decorators, e.g. @Component and @NgModule

import { NgModule, Component } from ‘@angular/core’;

 

@Component({

selector: ‘my-component’,

template: ‘<div>Class decorator</div>’,

})

export class MyComponent {

constructor() {

console.log(‘Hey I am a component!’);

}

}

 

@NgModule({

imports: [],

declarations: [],

})

export class MyModule {

constructor() {

console.log(‘Hey I am a module!’);

}

}

  1. Property decorators Used for properties inside classes, e.g. @Input and @Output

import { Component, Input } from ‘@angular/core’;

 

@Component({

selector: ‘my-component’,

template: ‘<div>Property decorator</div>’

})

 

export class MyComponent {

@Input()

title: string;

}

  1. Method decorators Used for methods inside classes, e.g. @HostListener

import { Component, HostListener } from ‘@angular/core’;

 

@Component({

selector: ‘my-component’,

template: ‘<div>Method decorator</div>’

})

export class MyComponent {

@HostListener(‘click’, [‘$event’])

onHostClick(event: Event) {

// clicked, `event` available

}

}

  1. Parameter decorators Used for parameters inside class constructors, e.g. @Inject

import { Component, Inject } from ‘@angular/core’;

import { MyService } from ‘./my-service’;

 

@Component({

selector: ‘my-component’,

template: ‘<div>Parameter decorator</div>’

})

export class MyComponent {

constructor(@Inject(MyService) myService) {

console.log(myService); // MyService

}

}

  • What is angular CLI?

Angular CLI(Command Line Interface) is a command line interface to scaffold and build angular apps using nodejs style (commonJs) modules. You need to install using below npm command,

npm install @angular/cli@latest

Below are the list of few commands, which will come handy while creating angular projects

  1. Creating New Project: ng new
  2. Generating Components, Directives & Services: ng generate/g The different types of commands would be,
  • ng generate class my-new-class: add a class to your application
  • ng generate component my-new-component: add a component to your application
  • ng generate directive my-new-directive: add a directive to your application
  • ng generate enum my-new-enum: add an enum to your application
  • ng generate module my-new-module: add a module to your application
  • ng generate pipe my-new-pipe: add a pipe to your application
  • ng generate service my-new-service: add a service to your application
  1. Running the Project: ng serve
  • What is the difference between constructor and ngOnInit?

TypeScript classes has a default method called constructor which is normally used for the initialization purpose. Whereas ngOnInit method is specific to Angular, especially used to define Angular bindings. Even though constructor getting called first, it is preferred to move all of your Angular bindings to ngOnInit method. In order to use ngOnInit, you need to implement OnInit interface as below,

export class App implements OnInit{

constructor(){

//called first time before the ngOnInit()

}

 

ngOnInit(){

//called after the constructor and called  after the first ngOnChanges()

}

}

  • What is a service?

A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components. Let’s create a repoService which can be used across components,

import { Injectable } from ‘@angular/core’;

import { Http } from ‘@angular/http’;

 

@Injectable() // The Injectable decorator is required for dependency injection to work

export class RepoService{

constructor(private http: Http){

}

 

fetchAll(){

return this.http.get(‘https://api.github.com/repositories’).map(res => res.json());

}

}

The above service uses Http service as a dependency.

  • What is dependency injection in Angular?

Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.

  • How is Dependency Hierarchy formed?
  • What is the purpose of async pipe?

The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value is emitted, the pipe marks the component to be checked for changes. Let’s take a time observable which continuously updates the view for every 2 seconds with the current time.

@Component({

selector: ‘async-observable-pipe’,

template: `<div><code>observable|async</code>:

Time: {{ time | async }}</div>`

})

export class AsyncObservablePipeComponent {

time = new Observable(observer =>

setInterval(() => observer.next(new Date().toString()), 2000)

);

}

  • What is the option to choose between inline and external template file?

You can store your component’s template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator’s templateUrl property. The choice between inline and separate HTML is a matter of taste, circumstances, and organization policy. But normally we use inline template for small portion of code and external template file for bigger views. By default, the Angular CLI generates components with a template file. But you can override that with the below command,

ng generate component hero -it

  • What is the purpose of ngFor directive?

We use Angular ngFor directive in the template to display each item in the list. For example, here we iterate over list of users,

<li *ngFor=”let user of users”>

{{ user }}

</li>

The user variable in the ngFor double-quoted instruction is a template input variable

  • What is the purpose of ngIf directive?

Sometimes an app needs to display a view or a portion of a view only under specific circumstances. The Angular ngIf directive inserts or removes an element based on a truthy/falsy condition. Let’s take an example to display a message if the user age is more than 18,

<p *ngIf=”user.age > 18″>You are not eligible for student pass!</p>

Note: Angular isn’t showing and hiding the message. It is adding and removing the paragraph element from the DOM. That improves performance, especially in the larger projects with many data bindings.

  • What happens if you use script tag inside template?

Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the text content of the <script> tag. This way it eliminates the risk of script injection attacks. If you still use it then it will be ignored and a warning appears in the browser console. Let’s take an example of innerHtml property binding which causes XSS vulnerability,

export class InnerHtmlBindingComponent {

// For example, a user/attacker-controlled value from a URL.

htmlSnippet = ‘Template <script>alert(“0wned”)</script> <b>Syntax</b>’;

}

  • What is interpolation?

Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding. It is represented by double curly braces({{}}). The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property. Let’s take an example,

<h3>

{{title}}

<img src=”{{url}}” style=”height:30px”>

</h3>

In the example above, Angular evaluates the title and url properties and fills in the blanks, first displaying a bold application title and then a URL.

  • What are template expressions?

A template expression produces a value similar to any Javascript expression. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive. In the property binding, a template expression appears in quotes to the right of the = symbol as in [property]=”expression”. In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}},

<h3>{{username}}, welcome to Angular</h3>

The below javascript expressions are prohibited in template expression

  1. assignments (=, +=, -=, …)
  2. new
  3. chaining expressions with ; or ,
  4. increment and decrement operators (++ and –)
  • What are template statements?

A template statement responds to an event raised by a binding target such as an element, component, or directive. The template statements appear in quotes to the right of the = symbol like (event)=”statement”. Let’s take an example of button click event’s statement

<button (click)=”editProfile()”>Edit Profile</button>

In the above expression, editProfile is a template statement. The below JavaScript syntax expressions are not allowed.

  1. new
  2. increment and decrement operators, ++ and —
  3. operator assignment, such as += and -=
  4. the bitwise operators | and &
  5. the template expression operators
  • How do you categorize data binding types?

Binding types can be grouped into three categories distinguished by the direction of data flow. They are listed as below,

  1. From the source-to-view
  2. From view-to-source
  3. View-to-source-to-view

The possible binding syntax can be tabularized as below,

Data direction Syntax Type
From the source-to-view(One-way) 1. {{expression}} 2. [target]=”expression” 3. bind-target=”expression” Interpolation, Property, Attribute, Class, Style
From view-to-source(One-way) 1. (target)=”statement” 2. on-target=”statement” Event
View-to-source-to-view(Two-way) 1. [(target)]=”expression” 2. bindon-target=”expression” Two-way
  • What are pipes?

A pipe takes in data as input and transforms it to a desired output. For example, let us take a pipe to transform a component’s birthday property into a human-friendly date using date pipe.

import { Component } from ‘@angular/core’;

 

@Component({

selector: ‘app-birthday’,

template: `<p>Birthday is {{ birthday | date }}</p>`

})

export class BirthdayComponent {

birthday = new Date(1987, 6, 18); // June 18, 1987

}

  • What is a parameterized pipe?

A pipe can accept any number of optional parameters to fine-tune its output. The parameterized pipe can be created by declaring the pipe name with a colon ( : ) and then the parameter value. If the pipe accepts multiple parameters, separate the values with colons. Let’s take a birthday example with a particular format(dd/mm/yyyy):

import { Component } from ‘@angular/core’;

 

@Component({

selector: ‘app-birthday’,

template: `<p>Birthday is {{ birthday | date | ‘dd/mm/yyyy’}}</p>` // 18/06/1987

})

export class BirthdayComponent {

birthday = new Date(1987, 6, 18);

}

Note: The parameter value can be any valid template expression, such as a string literal or a component property.

  • How do you chain pipes?

You can chain pipes together in potentially useful combinations as per the needs. Let’s take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below

import { Component } from ‘@angular/core’;

 

@Component({

selector: ‘app-birthday’,

template: `<p>Birthday is {{  birthday | date:’fullDate’ | uppercase}} </p>` // THURSDAY, JUNE 18, 1987

})

export class BirthdayComponent {

birthday = new Date(1987, 6, 18);

}

  • What is a custom pipe?

Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics,

  1. A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library For example,

@Pipe({name: ‘myCustomPipe’})

  1. The pipe class implements the PipeTransform interface’s transform method that accepts an input value followed by optional parameters and returns the transformed value. The structure of pipeTransform would be as below,

interface PipeTransform {

transform(value: any, …args: any[]): any

}

  1. The @Pipe decorator allows you to define the pipe name that you’ll use within template expressions. It must be a valid JavaScript identifier.

template: `{{someInputValue | myCustomPipe: someOtherValue}}`

  • Give an example of custom pipe?

You can create custom reusable pipes for the transformation of existing value. For example, let us create a custom pipe for finding file size based on an extension,

import { Pipe, PipeTransform } from ‘@angular/core’;

 

@Pipe({name: ‘customFileSizePipe’})

export class FileSizePipe implements PipeTransform {

transform(size: number, extension: string = ‘MB’): string {

return (size / (1024 * 1024)).toFixed(2) + extension;

}

}

Now you can use the above pipe in template expression as below,

template: `

<h2>Find the size of a file</h2>

<p>Size: {{288966 | customFileSizePipe: ‘GB’}}</p>

`

  • What is the difference between pure and impure pipe?

A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object). An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.

  • What is a bootstrapping module?

Every application has at least one Angular module, the root module that you bootstrap to launch the application is called as bootstrapping module. It is commonly known as AppModule. The default structure of AppModule generated by AngularCLI would be as follows,

/* JavaScript imports */

import { BrowserModule } from ‘@angular/platform-browser’;

import { NgModule } from ‘@angular/core’;

import { FormsModule } from ‘@angular/forms’;

import { HttpClientModule } from ‘@angular/common/http’;

 

import { AppComponent } from ‘./app.component’;

 

/* the AppModule class with the @NgModule decorator */

@NgModule({

declarations: [

AppComponent

],

imports: [

BrowserModule,

FormsModule,

HttpClientModule

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

  • What are observables?

Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

  • What is HttpClient and its benefits?

Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular provides a simplified client HTTP API known as HttpClient which is based on top of XMLHttpRequest interface. This client is avaialble from @angular/common/http package. You can import in your root module as below,

import { HttpClientModule } from ‘@angular/common/http’;

The major advantages of HttpClient can be listed as below,

  1. Contains testability features
  2. Provides typed request and response objects
  3. Intercept request and response
  4. Supports Observalbe APIs
  5. Supports streamlined error handling
  • Explain on how to use HttpClient with an example?

Below are the steps need to be followed for the usage of HttpClient.

  1. Import HttpClient into root module:

import { HttpClientModule } from ‘@angular/common/http’;

@NgModule({

imports: [

BrowserModule,

// import HttpClientModule after BrowserModule.

HttpClientModule,

],

……

})

export class AppModule {}

  1. Inject the HttpClient into the application: Let’s create a userProfileService(userprofile.service.ts) as an example. It also defines get method of HttpClient

import { Injectable } from ‘@angular/core’;

import { HttpClient } from ‘@angular/common/http’;

 

const userProfileUrl: string = ‘assets/data/profile.json’;

 

@Injectable()

export class UserProfileService {

constructor(private http: HttpClient) { }

}

 

getUserProfile() {

return this.http.get(this.userProfileUrl);

}

  1. Create a component for subscribing service: Let’s create a component called UserProfileComponent(userprofile.component.ts) which inject UserProfileService and invokes the service method,

fetchUserProfile() {

this.userProfileService.getUserProfile()

.subscribe((data: User) => this.user = {

id: data[‘userId’],

name: data[‘firstName’],

city:  data[‘city’]

});

}

Since the above service method returns an Observable which needs to be subscribed in the component.

  • How can you read full response?

The response body doesn’t may not return full response data because sometimes servers also return special headers or status code which which are important for the application workflow. Inorder to get full response, you should use observe option from HttpClient,

getUserResponse(): Observable<HttpResponse<User>> {

return this.http.get<User>(

this.userUrl, { observe: ‘response’ });

}

Now HttpClient.get() method returns an Observable of typed HttpResponse rather than just the JSON data.

  • How do you perform Error handling?

If the request fails on the server or failed to reach the server due to network issues then HttpClient will return an error object instead of a successful reponse. In this case, you need to handle in the component by passing error object as a second callback to subscribe() method. Let’s see how it can be handled in the component with an example,

fetchUser() {

this.userService.getProfile()

.subscribe(

(data: User) => this.userProfile = { …data }, // success path

error => this.error = error // error path

);

}

It is always a good idea to give the user some meaningful feedback instead of displaying the raw error object returned from HttpClient.

  • What is RxJS?

RxJS is a library for composing asynchronous and callback-based code in a functional, reactive style using Observables. Many APIs such as HttpClient produce and consume RxJS Observables and also uses operators for processing observables. For example, you can import observables and operators for using HttpClient as below,

import { Observable, throwError } from ‘rxjs’;

import { catchError, retry } from ‘rxjs/operators’;

  • What is subscribing?

An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Let’s take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.

Creates an observable sequence of 5 integers, starting from 1

const source = range(1, 5);

 

// Create observer object

const myObserver = {

next: x => console.log(‘Observer got a next value: ‘ + x),

error: err => console.error(‘Observer got an error: ‘ + err),

complete: () => console.log(‘Observer got a complete notification’),

};

 

// Execute with the observer object and Prints out each item

myObservable.subscribe(myObserver);

// => Observer got a next value: 1

// => Observer got a next value: 2

// => Observer got a next value: 3

// => Observer got a next value: 4

// => Observer got a next value: 5

// => Observer got a complete notification

  • What is an observable?

An Observable is a unique Object similar to a Promise that can help manage async code. Observables are not part of the JavaScript language so we need to rely on a popular Observable library called RxJS. The observables are created using new keyword. Let see the simple example of observable,

import { Observable } from ‘rxjs’;

 

const observable = new Observable(observer => {

setTimeout(() => {

observer.next(‘Hello from a Observable!’);

}, 2000);

});

  • What is an observer?

Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has below structure,

interface Observer<T> {

closed?: boolean;

next: (value: T) => void;

error: (err: any) => void;

complete: () => void;

}

A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below,

myObservable.subscribe(myObserver);

Note: If you don’t supply a handler for a notification type, the observer ignores notifications of that type.

  1. What is the difference between promise and observable?

Below are the list of differences between promise and observable,

Observable Promise
Declarative: Computation does not start until subscription so that they can be run whenever you need the result Execute immediately on creation
Provide multiple values over time Provide only one
Subscribe method is used for error handling which makes centralized and predictable error handling Push errors to the child promises
Provides chaining and subscription to handle complex applications Uses only .then() clause
  • What is multicasting?

Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. Let’s demonstrate the multi-casting feature,

var source = Rx.Observable.from([1, 2, 3]);

var subject = new Rx.Subject();

var multicasted = source.multicast(subject);

 

// These are, under the hood, `subject.subscribe({…})`:

multicasted.subscribe({

next: (v) => console.log(‘observerA: ‘ + v)

});

multicasted.subscribe({

next: (v) => console.log(‘observerB: ‘ + v)

});

 

// This is, under the hood, `s

  • How do you perform error handling in observables?

You can handle errors by specifying an error callback on the observer instead of relying on try/catch which are ineffective in asynchronous environment. For example, you can define error callback as below,

myObservable.subscribe({

next(num) { console.log(‘Next num: ‘ + num)},

error(err) { console.log(‘Received an errror: ‘ + err)}

});

  • What is the short hand notation for subscribe method?

The subscribe() method can accept callback function definitions in line, for next, error, and complete handlers is known as short hand notation or Subscribe method with positional arguments. For example, you can define subscribe method as below,

myObservable.subscribe(

x => console.log(‘Observer got a next value: ‘ + x),

err => console.error(‘Observer got an error: ‘ + err),

() => console.log(‘Observer got a complete notification’)

);

  • What are the utility functions provided by RxJS?

The RxJS library also provides below utility functions for creating and working with observables.

  1. Converting existing code for async operations into observables
  2. Iterating through the values in a stream
  3. Mapping values to different types
  4. Filtering streams
  5. Composing multiple streams
  • What are observable creation functions?

RxJS provides creation functions for the process of creating observables from things such as promises, events, timers and Ajax requests. Let us explain each of them with an example,

  1. Create an observable from a promise

import { from } from ‘rxjs’; // from function

const data = from(fetch(‘/api/endpoint’)); //Created from Promise

data.subscribe({

next(response) { console.log(response); },

error(err) { console.error(‘Error: ‘ + err); },

complete() { console.log(‘Completed’); }

});

  1. Create an observable that creates an AJAX request

import { ajax } from ‘rxjs/ajax’; // ajax function

const apiData = ajax(‘/api/data’); // Created from AJAX request

// Subscribe to create the request

apiData.subscribe(res => console.log(res.status, res.response));

  1. Create an observable from a counter

import { interval } from ‘rxjs’; // interval function

const secondsCounter = interval(1000); // Created from Counter value

secondsCounter.subscribe(n =>

console.log(`Counter value: ${n}`));

  1. Create an observable from an event

import { fromEvent } from ‘rxjs’;

const el = document.getElementById(‘custom-element’);

const mouseMoves = fromEvent(el, ‘mousemove’);

const subscription = mouseMoves.subscribe((e: MouseEvent) => {

console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);

});

  • What will happen if you do not supply handler for observer?

Normally an observer object can define any combination of next, error and complete notification type handlers. If you don’t supply a handler for a notification type, the observer just ignores notifications of that type.

  • What are angular elements?

Angular elements are Angular components packaged as custom elements(a web standard for defining new HTML elements in a framework-agnostic way). Angular Elements hosts an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs, thus, providing a way to use Angular components in non-Angular environments.

  • What is the browser support of Angular Elements?

Since Angular elements are packaged as custom elements the browser support of angular elements is same as custom elements support. This feature is is currently supported natively in a number of browsers and pending for other browsers.

Browser Angular Element Support
Chrome Natively supported
Opera Natively supported
Safari Natively supported
Firefox Natively supported from 63 version onwards. You need to enable dom.webcomponents.enabled and dom.webcomponents.customelements.enabled in older browsers
Edge Currently it is in progress
  • What are custom elements?

Custom elements (or Web Components) are a Web Platform feature which extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code. The browser maintains a CustomElementRegistry of defined custom elements, which maps an instantiable JavaScript class to an HTML tag. Currently this feature is supported by Chrome, Firefox, Opera, and Safari, and available in other browsers through polyfills.

  • Do I need to bootstrap custom elements?

No, custom elements bootstrap (or start) automatically when they are added to the DOM, and are automatically destroyed when removed from the DOM. Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular.

  • Explain how custom elements works internally?

Below are the steps in an order about custom elements functionality,

  1. App registers custom element with browser: Use the createCustomElement() function to convert a component into a class that can be registered with the browser as a custom element.
  2. App adds custom element to DOM: Add custom element just like a built-in HTML element directly into the DOM.
  3. Browser instantiate component based class: Browser creates an instance of the registered class and adds it to the DOM.
  4. Instance provides content with data binding and change detection: The content with in template is rendered using the component and DOM data. The flow chart of the custom elements functionality would be as follows,
  • How to transfer components to custom elements?

Transforming components to custom elements involves two major steps,

  1. Build custom element class: Angular provides the createCustomElement() function for converting an Angular component (along with its dependencies) to a custom element. The conversion process implements NgElementConstructor interface, and creates a constructor class which is used to produce a self-bootstrapping instance of Angular component.
  2. Register element class with browser: It uses customElements.define() JS function, to register the configured constructor and its associated custom-element tag with the browser’s CustomElementRegistry. When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance. The detailed structure would be as follows,
  • What are the mapping rules between Angular component and custom element?

The Component properties and logic maps directly into HTML attributes and the browser’s event system. Let us describe them in two steps,

  1. The createCustomElement() API parses the component input properties with corresponding attributes for the custom element. For example, component @Input(‘myInputProp’) converted as custom element attribute my-input-prop.
  2. The Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name. For example, component @Output() valueChanged = new EventEmitter() converted as custom element with dispatch event as “valueChanged”.
  • How do you define typings for custom elements?

You can use the NgElement and WithProperties types exported from @angular/elements. Let’s see how it can be applied by comparing with Angular component, The simple container with input property would be as below,

@Component(…)

class MyContainer {

@Input() message: string;

}

After applying types typescript validates input value and their types,

const container = document.createElement(‘my-container’) as NgElement & WithProperties<{message: string}>;

container.message = ‘Welcome to Angular elements!’;

container.message = true;  // <– ERROR: TypeScript knows this should be a string.

container.greet = ‘News’;  // <– ERROR: TypeScript knows there is no `greet` property on `container`.

  • What are dynamic components?

Dynamic components are the components in which components location in the application is not defined at build time.i.e, They are not used in any angular template. But the component is instantiated and placed in the application at runtime.

  • What are the various kinds of directives?

There are mainly three kinds of directives.

  1. Components — These are directives with a template.
  2. Structural directives — These directives change the DOM layout by adding and removing DOM elements.
  3. Attribute directives — These directives change the appearance or behavior of an element, component, or another directive.
  • How do you create directives using CLI?

You can use CLI command ng generate directive to create the directive class file. It creates the source file(src/app/components/directivename.directive.ts), the respective test file(.spec.ts) and declare the directive class file in root module.

Give an example for attribute directives?

Let’s take simple highlighter behavior as a example directive for DOM element. You can create and apply the attribute directive using below steps,

  1. Create HighlightDirective class with the file name src/app/highlight.directive.ts. In this file, we need to import Directive from core library to apply the metadata and ElementRef in the directive’s constructor to inject a reference to the host DOM element ,

import { Directive, ElementRef } from ‘@angular/core’;

 

@Directive({

selector: ‘[appHighlight]’

})

export class HighlightDirective {

constructor(el: ElementRef) {

el.nativeElement.style.backgroundColor = ‘red’;

}

}

  1. Apply the attribute directive as an attribute to the host element(for example,

)

<p appHighlight>Highlight me!</p>

  1. Run the application to see the highlight behavior on paragraph element

ng serve

 

 

 

What is AngularJS?

AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework.

  • AngularJS is a powerful JavaScript based development framework to create RICH Internet Application (RIA).
  • AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC (Model View Controller) way.
  • Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0.

 

What is data binding in AngularJS?

Data binding is the automatic synchronization of data between model and view components. ng-model directive is used in data binding.

What is scope in AngularJS?

Scopes are objects that refer to the model. They act as glue between controller and view.

What are the controllers in AngularJS?

Controllers are JavaScript functions that are bound to a particular scope. They are the prime actors in AngularJS framework and carry functions to operate on data and decide which view is to be updated to show the updated model based data.

What are the services in AngularJS?

AngularJS come with several built-in services. For example $http service is used to make XMLHttpRequests (Ajax calls). Services are singleton objects which are instantiated only once in app.

What are the filters in AngularJS?

Filters select a subset of items from an array and return a new array. Filters are used to show filtered items from a list of items based on defined criteria.

What is routing in AngularJS?

It is concept of switching views. AngularJS based controller decides which view to render based on the business logic.

What is deep linking in AngularJS?

Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.

Which are the core directives of AngularJS?

Following are the three core directives of AngularJS.

  • ng-app − This directive defines and links an AngularJS application to HTML.
  • ng-model − This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind − This directive binds the AngularJS Application data to HTML tags.

 

What are AngularJS expressions?

Expressions are used to bind application data to html. Expressions are written inside double braces like {{ expression}}. Expressions behave in same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and outputs the data where they are used.

How to make an ajax call using Angular JS?

AngularJS provides $http control which works as a service to make ajax call to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from server in the following manner:

functionstudentController($scope,$http){
varurl=”data.txt”;
$http.get(url).success(function(response){
$scope.students= response;
});
}

What is use of $routeProvider in AngularJS?

$routeProvider is the key service which set the configuration of urls, maps them with the corresponding html page or ng-template, and attaches a controller with the same.

What is $rootScope?

Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object. $rootScope is the parent of all of the scope variables.

What is a service?

Services are JavaScript functions and are responsible to do specific tasks only. Each service is responsible for a specific task for example, $http is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.

What are the differences between service and factory methods?

factory method is used to define a factory which can later be used to create services as and when required whereas service method is used to create a service whose purpose is to do some defined task.

What is provider?

provider is used by AngularJS internally to create services, factory etc. during config phase(phase during which AngularJS bootstraps itself). Below mention script can be used to create MathService that we’ve created earlier. Provider is a special factory method with a method get() which is used to return the value/service/factory.

//define a module
varmainApp=angular.module(“mainApp”,[]);

//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide){
$provide.provider(‘MathService’,function(){

this.$get=function(){
var factory ={};
factory.multiply=function(a, b){
return a * b;
}
return factory;
};

});
});

 

What is AngularJS? Can you explain it technically?

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. Angular’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.

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

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
Features:

  • AngularJS is a powerful JavaScript based development framework to create RICH Internet Application(RIA).
  • AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC(Model View Controller) way.
  • Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0. Overall, AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain

 

Explain AngularJS boot process?

Angular initializes automatically upon DOMContentLoaded event or when the angular.js script is downloaded to the browser and the document.readyState is set to complete. At this point AngularJS looks for the ng-app directive which is the root of angular app compilation and tells about AngularJS part within DOM. When the ng-app directive is found then Angular will:

1. Load the module associated with the directive.
2. Create the application injector.
3. Compile the DOM starting from the ng-app root element.

This process is called auto-bootstrapping.
Example:
<html>
<body ng-app=”myApp”>
<div ng-controller=”Ctrl”> Hello {{msg}}! </div>
<script src=”lib/angular.js”></script>
<script>
var app = angular.module(‘myApp’, []);
app.controller(‘Ctrl’, function ($scope) {
$scope.msg = ‘World’;
});
</script>
</body>
</html>

Explain what is directive and mention what the different types of Directive in AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng-.

  • ng-app − This directive starts an AngularJS Application.
  • ng-init − This directive initializes application data.
  • ng-model − This directive binds the value of HTML controls (input, select, textarea) to application data.
  • ng-repeat − This directive repeats html elements for each item in a collection.

 

Explain all the below given key features of AngularJS

  1. Scope: Scope is a JavaScript object that refers to the application model. It acts as a context for evaluating angular expressions. Basically, it acts as glue between controller and view. Scopes are hierarchical in nature and follow the DOM structure of your AngularJS app. AngularJS has two scope objects: $rootScope and $scope.

    b. Controller: AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.

    c. Model: Models are plain old JavaScript objects that represent data used by your app. Models are also used to represent your app’s current state.

    d. View: The view is responsible for presenting your models data to end user. Typically it is the HTML markup which exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings.

    e. Services: Services are singletons, which are objects that are instantiated only once per app (by the $injector). They provide an interface to keep together methods that relate to a specific function. AngularJS provides many inbuilt services for example, $http, $route, $window, $location etc. Each service is responsible for a specific task for example, $http is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.

    f. Data-binding: AngularJS data-binding is the most useful feature which saves you from writing boilerplate code (i.e. the sections of code which is included in many places with little or no alteration). Now, developers are not responsible for manually manipulating the DOM elements and attributes to reflect model changes. AngularJS provides two-way databinding to handle the synchronization of data between model and view.

    g. Directives: Directives might just be the killer feature of AngularJS. Directives allow us to extend the grammar of the web through reusable HTML elements, attributes, and classes. AngularJS directives are extended HTML attributes with the prefix ng-.

    h. Filters: Filters are used to change modify the data and can be clubbed in expression or directives using pipe character. AngularJS filters can be used to transform data:
    1.currency -Format a number to a currency format.
    2. filter – Select a subset of items from an array.
    3. lowercase – Format a string to lower case.
    4. orderBy – Orders an array by an expression.
    5. uppercase – Format a string to upper case.

What are the key differences between AngularJS and jQuery?

Framework
If you compare jQuery and Angular, the former is a library and the latter is a framework. You can plug the library in your project and either use it fully, partially or not use it all. It’s like a plugin, a supplement to your JS project. With a framework – you have to play by its rules, either use it fully or don’t use it all. Angular.js is a MVC framework, it has model, view and controller which is one of the most popular software development architectures today. When developing with Angular, you have to start from the ground up with your architecture in mind. Although it’s possible to add Angular to your existing project, it’s just add more complexity in the long run.

Don’t use Angular the jQuery way
There are thousands of jQuery plugins out there, it’s very to just plug something in and forget about it. Angular has different structure, it’s recommended to use directives instead. Try to develop “the angular way” instead of just patching the code with old good plugins. It’s not even necessary to add jQuery to your project, Angular comes with jqLite (simplified version of jQuery for basic DOM manipulation).

Single page application
The architecture of the Angular app is different, most of them are single page applications (SPA). Instead of loading all the code at once like we do with jQuery and showing and hiding different parts of the DOM, we load templates on demand (using http requests). That way the application stays more modular and easier to maintain, debug or update. I like the approach where you create controller, module, HTML template and CSS file for every view in your app.

Data Binding
Data binding is one of the best features in Angular.js (one way or two way binding). This makes data completely independent from the presentation, unlike in jQuery where your model (data) is the DOM. For example, data comes from HTTP request (http module), it’s added to the scope ($scope.data) in controller and rendered in HTML template as {{ data }}.
This way you as a developer know where data is coming from and where you need to go to make any changes. In jQuery if you have something like $(‘#data’).render(); it may render a whole new page and you won’t event know what it is or where this content came from.

Summary
Angular doesn’t replace jQuery, it doesn’t compete with jQuery, they both can be used in the same application. jQuery for DOM manipulation, Angular – for structure. In fact there is nothing better to do DOM manipulation than jQuery.

 

What is deep linking in AngularJS?

Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.

 

<!DOCTYPE html>

<html>

<head>

<link rel=”stylesheet” href=”style.css”>

<script type=”text/javascript” src=”angular.min.js”></script>

<script type=”text/javascript” src=”angular-route.min.js”></script>

</head>

<body>

<div ng-app=”DeepLinking”>

[ <a href=”#/welcome”>Welcome</a> | <a href=”#/settings”>Settings</a> ]

<hr/>

<div ng-view></div>

</div>

<script type=”text/javascript”>

angular.module(‘DeepLinking’, [“ngRoute”])

.config([‘$routeProvider’, function($routeProvider) {

$routeProvider

.when(‘/welcome’, {

template: ‘<html><body>Welcome!</body></html>’

})

.when(‘/settings’, {

template: ‘<html><body>Settings</body></html>’

});

}]);

</script>

</body>

</html>

 

What is jQLite?

jQLite is a subset of jQuery that is built directly into AngularJS. jQLite provides you all the useful features of jQuery. In fact it provides you limited features or functions of jQuery. By default AngularJS use jQLite which is the subset of jQuery. If you want to use jQuery then simply load the jQuery library before loading the AngularJS. By doing so, Angular will skip jQLite and will started to use jQuery library.

 

<!DOCTYPE html>

<html>

<head>

<script type=”text/javascript” src=”angular.min.js”></script>

</head>

<body ng-app=”app”>

<div ng-controller=”mainCtrl”>

<input type=”text” id=”txtName” value=”Akhilesh Ojha” />

<button type=”button” ng-click=”clickme()”>Click me</button>

</div>

<script type=”text/javascript”>

var app = angular.module(‘app’, []);

app.controller(“mainCtrl”, function($scope, $element) {

$scope.clickme = function() {

var elem = angular.element(document.querySelector(‘#txtName’));

console.log(elem.val()) // console the value of textbox

};

});

</script>

</body>

</html>

 

What are the disadvantages of AngularJS?

Following are the disadvantages of AngularJS.

  • Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure.
  • Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more.

 

Is AngularJS a templating system?

At the highest level, Angular does look like just another templating system. But there is one important reason why the Angular templating system is different, that makes it very good fit for application development: bidirectional data binding. The template is compiled in the browser and the compilation step produces a live view. This means you, the developers, don’t need to write code to constantly sync the view with the model and the model with the view as in other templating systems.

 

Explain Directives in AngularJS?

Answer

AngularJS directives are only used to extend HTML and DOM elements’ behavior. These are the special attributes, that start with ng- prefix, that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element.

AngularJS has a set of built-in directives like

  • ngBind,
  • ngModel
  • ngClass
  • ngApp
  • ngInit
  • ngRepeat

We can create our own directives for Angular to use them in our AngularJS Application with the controllers and services too. In this article, we’ll learn about some most important built-in directives like: ng-app, ng-init, ng-model, ng-bind and ng-repeat.

ng-app

It is the most important directive for an Angular Application, which is used to indicate starting of an Angular Application to AngularJS HTML compiler ($compile), like a “Main()” function in any compile time language like C#, Java or C++ etc. If we do not use this directive first and directly try to write other directives, it gives an error.

ng-init

ng-init directive is used to initialize an AngularJS Application data variable’s inline statement, so that we can use those in the specified block where we declare them. It is like a local member of that ng-app and it can be a value or a collection of the values and as an array, it directly supports JSON data.

ng-model

ng-model directive is used to define the model/variables value to be used in AngularJS Application’s HTML controls like <input type=’text’/> and it also provides two-way binding behavior with the model value. In some cases, it’s also used for databinding.

ng-bind

ng-bind directive is also used to bind the model/variable’s value to AngularJS Applications HTML controls as well as with HTML tags attributes like: <p/>, <span/> and more, but it does not support two way binding. We can just see the output of the model values.

ng-repeat

ng-repeat directive is used to repeat HTML statements. Ng-repeat works the same as for each loop in C#, Java or PHP on a specific collection item like an array.

What are expressions in AngularJS?

Answer

Expressions in AngularJS are just like JavaScript code snippets. JavaScript code is usually written inside double braces: {{expression}}. In other words, Angular Expressions are JavaScript code snippets with limited sub-set. Expressions are included in the HTML elements.

Like JavaScript expressions, AngularJS expressions can also have various valid expressions. We can use the operators between numbers and strings, literals, objects and arrarys inside the expression {{ }}. For example,

  • {{ 2 + 2 }} (numbers)
  • {{Name + ” ” + email}} (string)
  • {{ Country.Name }} (object)
  • {{ fact[4] }} (array)

Example

  1. <div ng-controller=”appController”>
  2.     <span>
  3. 4+5 = {{4+5}}
  4. </span>
  5.     <br />
  6.     <br />
  7.     <span ng-init=”quantity=5;cost=25″>
  8. Total Cost = {{quantity * cost}}
  9. </span>
  10. </div>

Explain currency filter in AngularJS

Answer

One of the filters in AngularJS is the Currency Filter. This “currency” filter includes the “$” Dollar Symbol as the default. So we can use the following code as the html template format of Currency Filter.

{{ currency_expression | currency : symbol : fractionSize}}

How to use Currency Filter in AngularJS

There are two ways by which we can use Currency Filter.

  • Default

    If we did not provide any currency symbol then by default Dollar-Sign will be used; we can use it as follows:

    <!– by default –>

    Default Currency {{amount | currency}}

  • User Defined

    To use different type of currency symbols we have to define our own symbol by using the unicode or Hexa-Decimal code of that Currency.

    E.g. – For Example If we want to define Indian Currency Symbol then we have to use (Unicode-value) or (Hexa-Decimal value)

What is $scope in AngularJS?

Answer

$scope in AngularJS is an object which refers to an application model. It is an object that binds view (DOM element) with the controller. In controller, model data is accessed via $scope object. As we know, AngularJS supports MV* pattern, $scope object becomes the model of MV*.

The $scope is a special JavaScript object. Both View and controller have access to the scope object. It can be used for communication between view and controller. Scope object contains both data and functions. Every AngularJS application has a $rootScope that is the top most scope created on the DOM element which contains the ng-app directive. It can watch expressions and propagate events.

Characteristics of scope object

  • It provides the APIs to observe model (example $watch).
  • It can be nested, so that it limits access to the properties. Nested scopes are either child scope or isolated scope.
  • It provides the APIs to propagate any model changes from the outside of “Angular realm” (example $apply).
  • It provides context against the expression to be evaluated.

Example

In the following example, I have created three controllers: parentController, firstChildControllerand secondChildController and defined one property in each controller; parentName, level1name, and level2name respectively. Here controllers are attached with DOM elements in a nested way.

As described above, AngularJS evaluates expressions with current associated scope and then it searches in parent scope and so on until the root scope is reached.

TestAngularJs.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>AngularJS Test Application</title>
  5.     <script src=”angular.js”></script>
  6. </head>
  7. <body ng-app=”myapp”>
  8.     <h2>AngularJS – Scope Inheritance</h2>
  9.     <div ng-controller=”ParentController”>
  10.         <div ng-controller=”firstChildController”>
  11.             <div ng-controller=”secondChildController”>
  12.                 <p>Parent Name:{{parentName}}</p>
  13.                 <p>First Child Name:{{level1name}}</p>
  14.                 <p>Second Child Name:{{level2name}}</p>
  15.             </div>
  16.         </div>
  17.     </div>
  18.     <script>
  19.         var app = angular.module(“myapp”, []);
  20.         app.controller(“ParentController”, function($scope)
  21.         {
  22.             $scope.parentName = “Parent Controller”;
  23.         });
  24.         app.controller(“firstChildController”, function($scope)
  25.         {
  26.             $scope.level1name = “First Child Controller”;
  27.         });
  28.         app.controller(“secondChildController”, function($scope)
  29.         {
  30.             $scope.level2name = “Second Child Controller”;
  31.         });
  32.     </script>
  33. </body>
  34. </html>

What is “$rootScope” in AngularJS?

Answer

A scope provides a separation between View and its Model. Every application has a $rootScope provided by AngularJS and every other scope is its child scope.

Using $Rootscope

Using rootscope we can set the value in one controller and read it from the other controller.

The following is the sample code snippet,

  1. <!DOCTYPE html>
  2. <html ng-app=”myApp”>
  3. <head>
  4.     <script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”>
  5.     </script>
  6.     <script>
  7.         var myApp = angular.module(‘myApp’, []);
  8.         function controllerOne($scope, $rootScope)
  9.         {
  10.             $rootScope.name = ‘From Rootscope set in controllerOne’;
  11.         }
  12.         function controllerTwo($scope, $rootScope)
  13.         {
  14.             $scope.name2 = $rootScope.name;
  15.         }
  16.     </script>
  17. </head>
  18. <body>
  19.     <div style=”border: 5px solid gray; width: 300px;”>
  20.         <div ng-controller=”controllerOne”>
  21.             Setting the rootscope in controllerOne
  22.         </div>
  23.         <div ng-controller=”controllerTwo”>
  24.             Hello, {{name2}}!
  25.         </div>
  26.         <br />
  27.     </div>
  28. </body>
  29. </html>

As we know, Rootscope is the top-level data container in AngularJs, we can keep any data in rootscope and read it when needed.

What is SPA (Single page application) in AngularJS?

Answer

Single-Page Applications (SPAs) are web applications that load a single HTML page and dynamically update that page as the user interacts with the app. SPAs use AJAX and HTML to create fluid and responsive web apps, without constant page reloads. However, this means much of the work happens on the client side, in JavaScript.

A single HTML page here means UI response page from the server. The source can be ASP, ASP.NET, ASP.NET MVC, JSP and so on.

A single-page web application, however, is delivered as one page to the browser and typically does not require the page to be reloaded as the user navigates to various parts of the application. This results in faster navigation, more efficient network transfers, and better overall performance for the end user.

Key Points of Single-Page Applications

  • The application is responsive in the UI with no page flicker
  • The Back/Forward buttons work as expected
  • More JavaScript than actual HTML
  • Dynamic data loading from the server-side API works with restful web service with JSON format
  • Rich interaction among UI components
  • Fewer data transfers from the server and most of the page processes in the UI occurs client-side.
  • The application contains tabs and subtabs with multiple HTML containers on the click of the tabs or subtabs and the specific portions of the page that are loaded into the page (the page will be one using the application)
  • Applications written in AngularJS are cross-browser compliant. Angular automatically handles the JavaScript code suitable for each browser.

How to implement routing in AngularJS?

Answer

Routing is a core feature in AngularJS. This feature is useful in building SPA (Single Page Application) with multiple views. In SPA application, all views are different Html files and we use Routing to load different parts of the application and it’s helpful to divide the application logically and make it manageable. In other words, Routing helps us to divide our application in logical views and bind them with different controllers.

How to add routing

The$routeProvider definition contained by the module is called “ngRoute”. In app.js file, I have defined an angular app using “angular. Module” method. After creating module, we need to configure the routes. The “config” method is used to configure $routeProvider. Using “when” and “otherwise” method of $routeProvider, we can define the route for our AngularJS application.

  1. var app = angular.module(“AngularApp”, [‘ngRoute’]);
  2. app.config([‘$routeProvider’,
  3.     function($routeProvider)
  4.     {
  5.         $routeProvider.
  6.         when(‘/page1’,
  7.              {
  8.                 templateUrl: ‘Modules/Page1/page1.html’,
  9.                 controller: ‘Page1Controller’
  10.             })
  11.             .
  12.         when(‘/page2’,
  13.              {
  14.                 templateUrl: ‘Modules/Page2/page2.html’,
  15.                 controller: ‘Page2Controller’
  16.             })
  17.             .
  18.         otherwise
  19.         ({
  20.             redirectTo: ‘/page1’
  21.         });
  22.     }
  23. ]);

How many types of data binding in AngularJS?

Answer

Data binding is a very powerful feature of the software development technologies. Data binding is the connection bridge between view and business logic (view model) of the application. Data binding in AngularJs is the automatic synchronization between the model and view. When the model changes, the view is automatically updated and vice versa. AngularJs support one-way binding as well as two-way binding.

Figure 1: One-Way and Two-Way Data Binding

Binding Directives in AngularJs

  • ng-bind
  • ng-bind-html
  • ng-bind-template
  • ng-non-bindable
  • ng-model

ng-bind

This directive updates the text content of the specified HTML element with the value of the given expression and the text content is changing on expression changes. It is very similar to double curly markup ( {{expression }}) but less verbose.

Syntax

  1. <ANY ELEMENT ng-bind=”expression”> </ANY ELEMENT>

Ng-bind-html

It (whatever it is) evaluates the expression and inserts the HTML content into the element in a secure way. It uses the $sanitize service, so to use this functionality, be sure that $sanitize is available.

Syntax

  1. <ANY ELEMENT ng-bind-html=” expression “> </ANY ELEMENT>

ng-bind-template

It (whatever it is) replaces the element text content with the interpolation of the template. It can contain multiple double curly markups.

Syntax

  1. <ANY ELEMENT ng-bind-template=” {{expression1}} {{expression2}} … {{expressionn}} “> </ANY ELEMENT>

ng-non-bindable

This (whatever “this” is) directive informs AngularJs to not compile or bind the contents of the current DOM element This element is useful when we want to display the expression but it should not be executed by AngularJs.

Syntax

<ANY ELEMENT ng-non-bindable > </ANY ELEMENT>

ng-model

This (whatever “this” is) directive can be bound with input, select, text area or any custom form control. It provides two-way binding. It also provides validation behavior. It also keeps the state of the control (valid/invalid, dirty/pristine, touched/untouched and so on).

Syntax

<input ng-bind=”expression”/>

What is a Factory method in AngularJS?

Answer

AngularJS Factory: the purpose of Factory is also the same as Service, however in this case we create a new object and add functions as properties of this object and at the end we return this object.

Factories module.factory( ‘factoryName’, function );

Example

  1. <div ng-app=”Myapp”>
  2.     <div ng-controller=”exampleCtrl”>
  3.         <input type=”text” ng-model=”num.firstnumber” />
  4.         <input type=”text” ng-model=”num.secondnumber” />
  5.         <input type=”button” ng-click=”Factoryclick()” value=”Factoryclick” />
  6.         <input type=”button” ng-click=”servclick()” value=”Serviceclick” /> factory result {{facresult}} service result {{secresult}}
  7.     </div>
  8. </div>
  9. var myapp = angular.module(‘Myapp’, []);
  10. myapp.controller(‘exampleCtrl’, [‘$scope’, ‘$http’, ‘factories’, ‘services’, function (scope, http, fac, ser)
  11. {
  12. scope.Factoryclick = function ()
  13. {
  14. var firstnumber = parseInt(scope.num.firstnumber);
  15. var secondnumber = parseInt(scope.num.secondnumber);
  16. scope.facresult = fac.sumofnums(firstnumber, secondnumber);
  17. }
  18. scope.servclick = function ()
  19. {
  20. var firstnumber = parseInt(scope.num.firstnumber);
  21. var secondnumber = parseInt(scope.num.secondnumber);
  22. debugger;
  23. scope.secresult = ser.sersumofnums(firstnumber, secondnumber);
  24. }
  25. }]);
  26. myapp.factory(‘factories’, function ($http)
  27. {
  28. return {
  29. sumofnums: function (a, b)
  30. {
  31. return a + b;
  32. }
  33. }
  34. });
  35. myapp.service(‘services’, function ($http)
  36. {
  37. debugger;
  38. this.sersumofnums = function (a, b)
  39. {
  40. return a + b;
  41. };
  42. });

When to use Factory: It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with a constructor function.

How are validations implemented in AngularJS?

Answer

One of the coolest features of AngularJS is client-side validation. There are so many form directives available in AngularJS. We will talk about some of them here, we will also explain custom validation. Using it you can create your own validations.

Initial requirement is reference,

  1. <script src=”~/Scripts/angular.js”></script>
  1. Data type validation

    a.In Html control use type field to specify the type of file.
    b..$error.{your data type} will help you to disply the message.

    1. <p>
    2.     <input type=”number” name=”StudentRollNumber” ng-model=”StudentRollNumber” required>
    3.     <span style=”color:red” ng- show=”myForm.StudentRollNumber.$dirty && myForm.StudentRollNumber.$invalid”>
    4. <span ng-show=”myForm.StudentRollNumber.$error.required”>Student Roll Number is required.</span>
    5.     <span ng-show=”myForm.StudentRollNumber.$error.number”>Not valid number!</span>
    6.     </span>
    7. </p>
  2. Required filed validation

    a. Put attribute as required in HTML control.
    b..$error.required helps you to display the required field message.

    1. <p>
    2.     <input type=”text” name=”Student” ng-model=”Student” required>
    3.     <span style=”color:red” ng-show=”myForm.Student.$dirty && myForm.Student.$invalid”>
    4. <span ng-show=”myForm.Student.$error.required”>Student Name is required.</span>
    5.     </span>
    6. </p>
  1. Date Validation

    a. Specify the type as date and
    b. Format it will take as systems built-in format
    c. .$error.date helps you to display the required field message.

    1. <p>
    2.     Student Birth Date:<br>
    3.     <input type=”date” name=”BirthDate” ng-model=”BirthDate” required placeholder=”yyyy-MM-dd”>
    4.     <span style=”color:red” ng-show=”myForm.BirthDate.$dirty && myForm.BirthDate.$invalid”>
    5. <span ng-show=”myForm.BirthDate.$error.required”>Student Birth Date is required.</span>
    6.     <span ng-show=”myForm.BirthDate.$error.date”>Not a Valid Date.</span>
    7.     </span>
    8. </p>
  1. Email Validation

    a. Specify the type as Email and
    b..$error.email helps you to display the required field message.

    1. <input type=”email” name=”email” ng-model=”email” required>
    2. <span style=”color:red” ng-show=”myForm.email.$dirty && myForm.email.$invalid”>
    3. <span ng-show=”myForm.email.$error.required”>Email is required.</span>
    4. <span ng-show=”myForm.email.$error.email”>Invalid email address.</span>
    5. </span>
  1. Range Validation Max and Min

    a. Specify Max or Min attribute
    b..$error.max or .$error.min helps you to display the error message.

    1. <input type=”number” name=”marks” ng-model=”marks” max=”100″ required>
    2. <span style=”color:red” ng-show=”myForm.marks.$dirty && myForm.marks.$invalid”>
    3. <span ng-show=”myForm.marks.$error.required”>Email is required.</span>
    4. <span ng-show=”myForm.marks.$error.number”>Invalid number.</span>
    5. <span ng-show=”myForm.marks.$error.max”>Max Percentage is 100.</span>

Explain what is Dependency Injection in AngularJS?

Answer

Dependency Injection is one of the best features of AngularJS. It is a software design pattern in which objects are passed as dependencies. It helps us to remove hard coded dependencies and makes dependencies configurable. Using Dependency Injection, we can make components maintainable, reusable and testable.

Dependency Injection is required for the following

  • Separating the process of creation and consumption of dependencies.
  • It allows us to create independent development of the dependencies.
  • We can change the dependencies when required.
  • It allows injecting mock objects as dependencies for testing.

AngularJS uses dependency with several types

  • Value
  • Factory
  • Service
  • Provider
  • Constant

A simple case of dependency injection in Angular js

  1. AppModule.controller(“AppController”, function($scope, $window, $log,$http)
  2. {
  3. });

Explain ng-repeat directive.

Answer

The ng-repeat directive is the most used and very useful AngularJS Directive feature. It iterates over a collection of items and creates DOM elements. It constantly monitors the source of data to re-render a template in response to change.

Syntax of ng-repeat

  1. <table class=”table table-bordered”>
  2.     <tr ng-repeat=”empin empDetails”>
  3.         <td>{{emp.name}}</td>
  4.         <td>{{emp.salary}}</td>
  5.     </tr>
  6. </table>

Here, ng-repeat directive iterates over the empDetails collection and creates a <tr> DOM element for each entry in the collection.

The ng-repeat directive creates a new scope for each element of a collection.

Variables created by ng-repeat

AngularJS ng-repeat directive creates so many special variables in a scope created for each and every individual entry. These variables are very important to find the position of an element within a collection.

Below are the some important variables created by ng-repeat

  1. $index
  2. $first
  3. $middle
  4. $last

What is controller in AngularJS?

Answer

A controller is a set of JavaScript functions which is bound to a specified scope, the ng-controllerdirective. Angular will instantiate the new controller object, and injects the new scope as a dependency. It contains business logic for the view and avoids using controller to manipulate the DOM.

Controller Rules

  • We can use controller to set up the initial state of the scope object and add behavior to that object.
  • We do not use controller to manipulate DOM. It should contain only business logic and can use data binding and directives for the DOM manipulation.
  • We do not use controllers to format input but can use angular from controls instead of that.
  • We do not use filter output but can use angular filters instead of that.
  • We do not use controllers to share code or state across controllers but can use angular services instead of that.
  • We do not manage the life-cycle of other components.

Creating a Controller

  • Requires ng-controller directive.
  • Add controller code to a module.
  • Name your controller based on functionality.
  • Controllers are named using camel case (i.e. SimpleController).
  • Setup the initial state of the scope object.

ng-Controller directive

ng-Controller directive is an associated controller class to the view.

How to use ng-Controller

  1. <Any ng-Controller=”expression”>
  2. </Any>
  3. <div ng-app=”mainApp” ng-controller=”SimpleController”>

What are the filters in AngularJS?

Answer

Filters are used to modify the data and can be clubbed in expression or directives using a pipe character. A filter formats the value of an expression for display to the user. They can be used in view templates, controllers, or services, and we can easily create our own filter. Filter is a module provided by AngularJS. There are nine components of filter which are provided by AngularJS. We can write custom as well.

  • currency
  • date
  • filter
  • json
  • limitTo
  • lowercase
  • number
  • orderBy
  • uppercase

Currency It will change all the digits to currency and “$” is the default currency.

{{ x | currency}}

Output

Date

It will change all the digits into the date according to some rules, like the default date will be “44 years 2 months 10 days” earliar and 1000 will add 1 second into it.

{{ x | date:’medium’ }}

Output Change the 1 and 1000 into dates.

Filter

{{ filter_expression | filter : expression : comparator}}

limitTo

It will show the values depending on the limit of an array variable that has been set.

{{ names | limitTo:2 }}

Output

Here the limit is 2, so you can only see 2 values.

lowercase

It will change all the letters into lowercase as in the following:

{{ x | lowercase }}

Output

Number

It will show all the digits with 3 decimal places by default as in the following:

{{ x | number:8}}

Output I am using 8 here.

OrderBy

{{ orderBy_expression | orderBy : expression : reverse}}

uppercase

It will change all the letters to uppercase.

{{ x | uppercase }}

Output

Explain Module And Controller In AngularJS.

Answer

AngularJS module is nothing but a container of all angular components like controller, services, directive, filter, config etc

What is Module

Let me explain why module is required in AngularJS. In .NET console application there is a main method and what main method does is, it’s an entry point of application. It is the same as angular module and is an entry point. Using module we can decide how the AngularJS application should be bootstrapped.

We can create a simple module using the following code.

  1. var myApp = angular.module(‘myModuleApp’,[]);

In the above code myModuleApp is the module name and if this module is dependent on other modules we can inject in “[]”.

What is Controller?

Controller is a JavaScript constructor function which controls the data. I am not going to cover what are the types of functions in this article but let me give some brief information about constructor function. In constructor function when we call that function that function creates a new object each time.

Let’s make a controller.

  1. myApp.controller(‘myController’, function($scope)
  2. {
  3. });

What are the services in AngularJS?

Answer

Services are one of the most important concepts in AngularJS. In general services are functions that are responsible for specific tasks in an application. AngularJS services are designed based on two principles.

  1. Lazily instantiated

    Angular only instantiates a service when an application component depends on it using dependency injection for making the Angular codes robust and less error prone.

  2. Singletons

    Each component is dependent on a service that gets a reference to the single instance generated by the service factory.

    AngularJS provides many built in services, for example, $http, $route, $window, $location and so on. Each service is responsible for a specific task, for example, $http is used to make an Ajax call to get the server data. $route defines the routing information and so on. Builtin services are always prefixed with the $ symbol.

AngularJS internal services

AngularJS internally provides many services that we can use in our application. $http is one example. There are other useful services, such as $route, $window, $location and so on. Some of the commonly used services in any AngularJS applications are listed below.

  • $window Provide a reference to a DOM object.
  • $Location Provides reference to the browser location.
  • $timeout Provides a reference to window.settimeout function.
  • $Log Used for logging.
  • $sanitize Used to avoid script injections and display raw HTML in page.
  • $Rootscope Used for scope hierarchy manipulation.
  • $Route Used to display browser based path in browser URL.
  • $Filter Used for providing filter access.
  • $resource Used to work with Restful API.
  • $document Used to access the window. Document object.
  • $exceptionHandler Used for handling exceptions.
  • $q: Provides a promise object.

Explain double click event in AngularJS?

Answer

ng-dblclick allows you to specify custom behavior on a double-click event of the mouse on the web page. We can use it (ng-dblclick) as an attribute of the HTML element like,

  1. <ANY_HTML_ELEMENT ng-dblclick=”{expression}”>
  2. </ANY_HTML_ELEMENT>

Use the following procedure to create a sample of a double-click event using AngularJS.

First of all you need to add an external Angular.js file to your application, for this you can go to the AngularJS official site or download my source code and then fetch it or click on this link and download it: ANGULARJS. After downloading the external file you need to add this file to the Head section of your application as in the following,

Complete Code

  1. <!doctype html>
  2. <html ng-app>
  3. <head>
  4.     <script src=”angular.min.js”></script>
  5. </head>
  6. <body>
  7.     Name:
  8.     <input ng-model=”name” type=”text” />
  9.     <button ng-dblclick=”Msg=’Hello ‘+name”>
  10. Double Click
  11. </button>
  12.     </br>
  13.     <h3>
  14. {{Msg}}</h3>
  15. </body>
  16. </html>

Output

  • Initially when Page loads
  • Before double-click
  • After double-click

Explain ng-include, Click, and Repeat directive in AngularJS.

Answer

ng-include is an AngularJS directive, it is very helpful to include the various files in a main page using the ng-include attribute.

For example, you have one page layout that contains a header, body, footer and so on. In that scenario, you can create various HTML files for a header and footer then you can include those in the main HTML file. Because of this implementation the page looks cleaner and the code/design is also separated.

ng-click

This is also one of the directives; you can use this in one of the scenarios like when you click on a button. If you do any operation then this will be useful.

The form contains an input text box and Search button, whenever the user enters a value into a text box and clicks on the search button you need to display the user-entered value, if the user clicks on the search button without entering anything then we need to display a message.

The index.html file looks as in the following.

ng-repeat

This directive is like a foreach loop in C#. By using this directive you can display a collection of items in a view (HTML page).

You can display a list of employees using the ng-repeat directive in AngularJS.

  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <!– 1. Angular JS Script CDN reference added –>
  5.         <script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js”></script>
  6.         <!– 2. Script JS Reference –>
  7.         <script src=”Employee.js”></script>
  8.     </head>
  9.     <!– 3. ng-app directive included –>
  10.     <body ng-app=”DemoRepeatApp”>
  11.         <h1>List of Emplooyees</h1>
  12.         <!– 4. ng-controller directive included –>
  13.         <form ng-controller=”DemoController”>
  14.             <table>
  15.                 <thead>
  16.                     <tr>
  17.                         <th>Name</th>
  18.                         <th>Designation</th>
  19.                         <th>Location</th>
  20.                     </tr>
  21.                 </thead>
  22.                 <tbody>
  23.                     <!– 5. ng-repeat directive included –>
  24.                     <tr ng-repeat=”emp in employees”>
  25.                         <td>{{emp.Name}}</td>
  26.                         <td>{{emp.Designation}}</td>
  27.                         <td>{{emp.Location}}</td>
  28.                     </tr>
  29.                 </tbody>
  30.             </table>
  31.         </form>
  32.     </body>
  33. </html>

Explain ng-app directive.

Answer

ng-app directive is used to define AngularJS applications. We can use this to auto-bootstrap an AngularJS application. It designates the root element of AngularJS application and is generally kept near the  <body> or <html> tag. We can define any number of ng-app directives inside the HTML document but only one AngularJS application can be bootstrapped automatically (auto-bootstrapped); the other applications needs to be bootstrapped manually.

Example

  1. <div ng-app=”myApp” ng-controller=”myCtrl”>
  2. First Name :
  3.     <input type=”text” ng-model=”firstName”>
  4.         <br />
  5. Middle Name:
  6.         <input type=”text” ng-model=”middleName”>
  7.             <br />
  8. Last Name :
  9.             <input type=”text” ng-model=”lastName”>
  10.                 <br>
  11. Full Name: {{firstName + ” ” + middleName + ” ” + lastName }}
  12.                 </div>

Why are we using AngularJS and what are the advantages of AngularJS?

Answer

As we know AngularJS follows the  MVW* pattern and it allows us  to build well-structured, testable, and maintainable front end applications.

Note W* means “whatever,” in place of which we use C (controller) or VM (view model)

Why we are using AngularJS

  1. As we know AngularJS is based on MVC pattern; it helps us to organize our web apps or web application properly.
  2. It helps to make responsive and well organized web applications that are more expansive and readable.
  3. It follows two way data binding. Two way data binding helps us so that any changes in model will be updated view and vice-versa without any manipulation on DOM or events.
  4. AngularJS supports create your own directive that makes reusable components to be used according to your requirement. It is also abstract DOM manipulation logic.
  5. It supports services and dependency injection which we can easily inject in our controller and provides some utility code as per our requirement.

Advantages of AngularJS

  1. AngularJS has code reusability that allows us to write code & reuse it as required as Custom directive.
  2. AngularJS supports powerful data binding; it is two way data binding with the help of HTML & scope.
  3. AngularJS is easily customizable as per our requirement. Here we can create own custom components like directive and services.
  4. AngularJS has good support over the internet and over time it has new changes available for developers. It also supports IE, Opera, Safari, and Chrome.
  5. AngularJS has inbuilt form validation & template with all old plain html.
  6. AngularJS has easily testable Unit testing, it  doesn’t need to load all the app, just loading that specific module is enough to start unit testing.

What is Representational State Transfer(REST) in AngularJS.

Answer

REST is a style of API that operates over HTTP requests. The requested URL identifies the data to be operated on, and the HTTP method identifies the operation that is to be performed. REST is a style of API rather than a formal specification, and there is a lot of debate and disagreement about what is and isn’t RESTful, a term used to indicate an API that follows the REST style. AngularJS is pretty flexible about how RESTful web services are consumed. You should use the services that I describe in this article when you are performing data operations on a RESTful API. You may initially prefer to use the $http service to make Ajax requests, especially if you are coming from a jQuery background. To that end, I describe the use of $http at the start of the article, before explaining its limitations when used with REST and the advantages of using the $resource service as an alternative. For this, we first need to create a RESTful web API.

A REST web service is said to be RESTful when it adheres to the following constrants:

  • It’s URL-based (e.g., http://www.micbutton.com/rs/blogPost).
  • It uses an Internet media type such as JSON for data interchange.
  • It uses standard HTTP methods (GET, PUT, POST, DELETE).

HTTP methods have a particular purpose when used with REST services. The following is the standard way that HTTP methods should be used with REST services,

POST should be used to,

  1. Create a new resource.
  2. Retrieve a list of resources when a large amount of request data is required to be passed to the service.
  3. PUT should be used to update a resource.
  4. GET should be used to retrieve a resource or a list of resources.
  5. DELETE should be used to delete a resource.

For doing this, we first create a model class with the below mention members

Name Type Required
name String Yes
category String Yes
price number Yes

 

Explain ng-Switch Directive in AngularJS.

Answer

This directive is used to swap DOM structure conditionally in our template based on a scope expression. ngSwitchWhen or ngSwitchDefault directives are used to show and hide the element within ngSwitch directive. We can show or hide the element inside this directive and are required to place a “when” attribute per element. The “when” attribute is used to inform the ngSwitch directive which element is to display based on expression, if the matching expression is found, the element is displayed, else it is hidden.

Example

HTML

  1. <h4>ngSwitch Example</h4>
  2. <div ng-controller=”HelloController”>
  3.  Employee Name:
  4.     <select ng-model=”selection” ng-options=”name for name in names”></select>
  5.     <div ng-switch on=”selection”>
  6.         <div ng-switch-when=”Tejas”>You have select “Tejas”</div>
  7.         <div ng-switch-when=”Rakesh”>You have select “Rakesh”</div>
  8.         <div ng-switch-when=”Jignesh”>You have select “Jignesh”</div>
  9.         <div ng-switch-default>Please select name</div>
  10.     </div>
  11. </div>

Controller

  1. var app = angular.module(“app”, []);
  2. app.controller(“HelloController”, function($scope)
  3. {
  4.     $scope.names = [‘Tejas’, ‘Jignesh’, ‘Rakesh’];
  5. });

Output

Why we use $http service or ajax request in AngualrJS?

Answer

Ajax is the foundation of the modern web application, and you will use the services that I describe in this article every time that you need to communicate with a server without causing the browser to load new content and, in doing so, dump your AngularJS application. That said, if you are consuming data from a RESTful API, then you should use the $resource service. I will describe REST and $resource in the next article, but the short version is that $resource provides a higher-level API that is built on the services I describe in this article and makes it easier to perform common data operations.

Making Ajax Requests

The $http service is used to make and process Ajax requests, which are standard HTTP requests that are performed asynchronously.

The first—and most common—is to use one of the convenience methods that the service defines, which I have described in the below table and which allows you to make requests using the most commonly needed HTTP methods.

Name Descriptions
get(url, config) Performs a GET request for the specified URL.
post(url, data, config) Performs a POST request to the specified URL to submit the specified data.
delete(url, config) Performs a DELETE request to the specified URL.
put(url, data, config) Performs a PUT request with the specified data and URL.
patch(url, data, config) Performs a PATCH request with the specified data and URL.
head(url, config) Performs a HEAD request to the specified URL.
jsonp(url, config) Performs a GET request to obtain a fragment of JavaScript code that is then executed. JSONP, which stands for JSON with Padding, is a way of working around the limitations that browsers apply to where JavaScript code can be loaded from.

The other way to make an Ajax request is to treat the $http service object as a function and pass in a configuration object.

Configuring Ajax Requests

The methods defined by the $http service all accept an optional argument of an object containing configuration settings. For most applications, the default configuration used for Ajax requests will be fine, but you can adjust the way the requests are made by defining properties on the configuration object corresponding to the below table.

Name Descriptions
data Sets the data sent to the server. If you set this to an object, AngularJS will serialize it to the JSON format.
headers Used to set request headers. Set headers to an object with properties whose names and values correspond to the headers and values you want to add to the request.
method Sets the HTTP method used for the request.
params Used to set the URL parameters. Set params to an object whose property names and values correspond to the parameters you want to include.
timeout Specifies the number of milliseconds before the request expires. transformRequest Used to manipulate the request before it is sent to the server.
transformResponse Used to manipulate the response when it arrives from the server
url Sets the URL for the request.
withCredentials When set to true, the withCredentials option on the underlying browser request object is enabled, which includes authentication cookies in the request.

The most interesting configuration feature is the ability to transform the request and response through the aptly named transformRequest and transformResponse properties. AngularJS defines two built-in transformations; outgoing data is serialized into JSON, and incoming JSON data is parsed into JavaScript objects.

Html file code

  1. <!DOCTYPE html>
  2. <html ng-app=”TestApp”>
  3.     <head>
  4.         <title>AngularJS AJax </title>
  5.         <script src=”angular.js”></script>
  6.         <link href=”../../RefStyle/bootstrap.min.css” rel=”stylesheet” />
  7.         <script src=”app.js”></script>
  8.         <script src=”ajax_config.js”></script>
  9.     </head>
  10.     <body ng-controller=”ajaxController”>
  11.         <div class=”panel panel-default”>
  12.             <div class=”panel-body”>
  13.                 <table class=”table table-striped table-bordered”>
  14.                     <thead>
  15.                         <tr>
  16.                             <th>Name</th>
  17.                             <th>Category</th>
  18.                             <th>Price</th>
  19.                         </tr>
  20.                     </thead>
  21.                     <tbody>
  22.                         <tr ng-hide=”products.length”>
  23.                             <td colspan=”4″ class=”text-center”>No Data</td>
  24.                         </tr>
  25.                         <tr ng-repeat=”item in products”>
  26.                             <td>{{item.Category}}</td>
  27.                             <td>{{item.Book}}</td>
  28.                             <td>{{item.Publishers}}</td>
  29.                             <td>{{item.price | currency}}</td>
  30.                         </tr>
  31.                     </tbody>
  32.                 </table>
  33.                 <p>
  34.                     <button class=”btn btn-primary” ng-click=”loadData()”>
  35. Load Data
  36. </button>
  37.                     <button class=”btn btn-primary” ng-click=”loadXMLData()”>
  38. Load Data (XML)
  39. </button>
  40.                 </p>
  41.             </div>
  42.         </div>
  43.     </body>
  44. </html>

AngularJS file code

  1. testApp.controller(“ajaxController”, function($scope, $http)
  2. {
  3.     $scope.loadData = function()
  4.     {
  5.         $http.get(“data.json”).success(function(data)
  6.         {
  7.             $scope.products = data;
  8.         });
  9.     }
  10.     $scope.loadXMLData = function()
  11.     {
  12.         var config =
  13.             {
  14.             transformResponse: function(data, headers)
  15.               {
  16.                 if ((headers(“content-type”) == “application/xml” || headers(“content-type”) == “text/xml”) && angular.isString(data)) {
  17.                     products = [];
  18.                     var productElems = angular.element(data.trim()).find(“product”);
  19.                     for (var i = 0; i < productElems.length; i++)
  20.                     {
  21.                         var product = productElems.eq(i);
  22.                         products.push
  23.                         ({
  24.                             Category: product.attr(“Category”),
  25.                             Book: product.attr(“Book”),
  26.                             Publishers: product.attr(“Publishers”),
  27.                             price: product.attr(“price”)
  28.                         });
  29.                     }
  30.                     return products;
  31.                 } else
  32.                 {
  33.                     return data;
  34.                 }
  35.             }
  36.         }
  37.         $http.get(“data.xml”, config).success(function(data)
  38.          {
  39.             $scope.products = data;
  40.         });
  41.     }
  42. });
  1. Why to use AngularJS Global Object services?

    Answer

    The main reason that AngularJS includes these services is to make testing easier, but an important facet of unit testing is the need to isolate a small piece of code and test its behavior without testing the components it depends on—in essence, creating a focused test. The DOM API exposes functionality through global objects such as document and window.

    These objects make it hard to isolate code for unit testing without also testing the way that the browser implements its global objects. Using services such as $document allows AngularJS code to be written without directly using the DOM API global objects and allows the use of AngularJS testing services to configure specific test scenarios.

    The followings are the services that expose DOM API features.

Name Descriptions
$anchorScroll Scrolls the browser window to a specified anchor
$document Provides a jqLite object that contains the DOM window.document object
$interval Provides an enhanced wrapper around the window.setInterval function
$location Provides access to the URL
$log Provides a wrapper around the console object
$timeout Provides an enhanced wrapper around the window.setITimeout function
$window Provides a reference to the DOM window object

 

When and Why to use and create Services?

Answer

Services are used to encapsulate functionality that we need to reuse in an application but don’t fit clearly into Model-View-Controller pattern as we discussed in the article. Services are mainly used for the purpose of cross cutting concerns. The AngularJS Module defines three methods for defining services : factory, service and provider. The result of using these methods is the same – a service object that provides functionality that can be used throughout the AngularJS application – but the way that the service object is created and managed by each method is slightly different. Below I mentioned the built in services of AngularJS.

Name Descriptions
$anchorScroll Scrolls the browser window to a specified anchor
$animate Animates the content transitions.
$compile Processes an HTML fragment to create a function that can be used to generate content.
$controller A wrapper around the $injector service that instantiates controllers
$document Provides a jqLite objects that contains the DOM window.documentobject.
$exceptionHandler Handles exceptions that arise in the application.
$filter Provides access to filters
$http Creates and manages Ajax requests
$injector Creates instances of AngularJS components
$interpolate Processes a string that contains binding expressions to create a function that can be used to
generate content.
$interval Provides an enhanced wrapper around the window.setInterval function.
$location Provides a wrapper around the browser location object.
$log Provides a wrapper around the global console object.
$parse Processes an expression to create a function that can be used togenerate content.
$provide Implements many of the methods that are exposed by Module.
$q Provides deferred objects/promises.
$resource Provides support for working with RESTful APIs.
$rootElement Provides access to the root element in the DOM.
$rootScope Provides access to the top of the scope hierarchy
$route Provides support for changing view content based on the browser’sURL path.
$routeParams Provides information about URL routes.
$sanitize Replaces dangerous HTML characters with their display-safecounterparts.
$swipe Recognizes swipe gestures.
$timeout Provides an enhanced wrapper around the window.setITimeout function.
$window Provides a reference to the DOM window object.

I will discuss about this built in service of AngularJS in a later article. The main focus of this article is what are the different ways to create custom services as per our requirement in AngularJS.

Using Factory method

The simplest method of defining a service is to use the Module.factory method, passing an argument, the name of the service and a factory function that returns the service objects. For doing this, we create three files as follows,

ServiceApp.Js

  1. var serviceApp = angular.module(‘ServiceApp’, []);
  2. serviceApp.factory(“logService”, function()
  3. {
  4.     var messageCount = 0;
  5.     return
  6.     {
  7.         log: function(msg)
  8.         {
  9.             console.log(“(LOG + ” + messageCount++ + “) ” + msg);
  10.         }
  11.     };
  12. });

In the above file, I first create an angular module named serviceApp for defining the factory service which creates log message on execution.

App.js

  1. var testApp = angular.module(‘TestApp’, [‘ServiceApp’]);

Now, I define another angualr module named testApp in which I inject the ServiceApp module. This testApp module will be used from html page for controller.

Factory.html

  1. <!DOCTYPE html>
  2. <html ng-app=”TestApp”>
  3.     <head>
  4.         <title>AngularJS Factory</title>
  5.         <script src=”angular.js”></script>
  6.         <link href=”../../RefStyle/bootstrap.min.css” rel=”stylesheet” />
  7.         <script src=”serviceApp.js”></script>
  8.         <script src=”app.js”></script>
  9.         <script src=”Factory.js”></script>
  10.     </head>
  11.     <body ng-controller=”FactoryController”>
  12.         <div class=”well”>
  13.             <div class=”btn-group” tri-button counter=”data.totalClicks” source=”data.device”>
  14.                 <button class=”btn btn-default” ng-repeat=”item in data.device”>
  15.  {{item}}
  16.  </button>
  17.             </div>
  18.             <h5>Total Clicks: {{data.totalClicks}}</h5>
  19.         </div>
  20.     </body>
  21. </html>

Factory.js

  1. testApp.controller(‘FactoryController’, function($scope, logService)
  2. {
  3.     $scope.data =
  4.       {
  5.         device: [“Mobile”, “Laptops”, “IPad”],
  6.         totalClicks: 0
  7.     };
  8.     $scope.$watch(‘data.totalClicks’, function(newVal)
  9.     {
  10.         logService.log(“Total click count: ” + newVal);
  11.     });
  12. });
  13. testApp.directive(“triButton”, function(logService)
  14. {
  15.     return
  16.     {
  17.         scope:
  18.         {
  19.             counter: “=counter”
  20.         },
  21.         link: function(scope, element, attrs)
  22.         {
  23.             element.on(“click”, function(event)
  24.             {
  25.                 logService.log(“Button click: ” + event.target.innerText);
  26.                 scope.$apply(function()\
  27.                 {
  28.                     scope.counter++;
  29.                 });
  30.             });
  31.         }
  32.     }
  33. });

The output is as follows,
Explain Provider Method in AngularJS.

Answer

The Module.provider method allows you to take more control over the way that a service object is created or configured. The arguments to the provider method are the name of the service that is being defined and a factory function. The factory function is required to return a provider object that defines a method called $get, which in turn is required to return the service object. When the service is required, AngularJS calls the factory method to get the provider object and then calls the $get method to get the service object. Using the provider method doesn’t change the way that services are consumed, which means that I don’t need to make any changes to the controller or directive in the example.

The advantage of using the provider method is that you can add functionality to the provider method that can be used to configure the service object.

To demonstrate this process, I again change the serviceapp.js file as below,

  1. var serviceApp = angular.module(‘ServiceApp’, []);
  2. serviceApp.provider(“logService”, function()
  3. {
  4.     var counter = true;
  5.     var debug = true;
  6.     return
  7.     {
  8.         messageCounterEnabled: function(setting)
  9.       {
  10.             if (angular.isDefined(setting))
  11.             {
  12.                 counter = setting;
  13.                 return this;
  14.             } else
  15.             {
  16.                 return counter;
  17.             }
  18.         },
  19.         debugEnabled: function(setting)
  20.       {
  21.             if (angular.isDefined(setting))
  22.             {
  23.                 debug = setting;
  24.                 return this;
  25.             } else
  26.             {
  27.                 return debug;
  28.             }
  29.         },
  30.         $get: function()
  31.       {
  32.             return
  33.             {
  34.                 messageCount: 0,
  35.                 log: function(msg)
  36.               {
  37.                     if (debug)
  38.                     {
  39.                         console.log(“(LOG” + (counter ? ” + ” + this.messageCount++ + “) ” : “) “) + msg);
  40.                     }
  41.                 }
  42.             };
  43.         }
  44.     }
  45. });

What is event handling in AngularJS?

Answer

When we want to create advanced AngularJS applications such as User Interaction Forms, then we need to handle DOM events like mouse clicks, moves, keyboard presses, change events and so on. AngularJS has a simple model for how to add event listeners. We can attach an event listener to an HTML element using one of the following AngularJS event listener directives.

  • ng-click
  • ng-dbl-click
  • ng-mousedown
  • ng-mouseup
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-mouseover
  • ng-keydown
  • ng-keyup
  • ng-keypress
  • ng-change

Here is a simple AngularJS event listener directive example,

  1. @{
  2. Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6.     <head>
  7.         <meta name=”viewport” content=”width=device-width” />
  8.         <title>Acgular Event</title>
  9.         <script src=”~/Scripts/angular.js”></script>
  10.         <script>
  11. angular.module(“myapp”, [])
  12. .controller(“Controller1”, function ($scope) {
  13. $scope.myData = {};
  14. $scope.myData.dvClick = function () {
  15. alert(“Div clicked”);
  16. }
  17. });
  18. </script>
  19.     </head>
  20.     <body ng-app=”myapp”>
  21.         <div ng-controller=”Controller1″>
  22.             <div ng-click=”myData.dvClick()”>Click here</div>
  23.         </div>
  24.     </body>
  25. </html>

When we click the text within the div, the myData.dvClick() function will be called. As you can see in the controller function, the myData object has a dvClick() function added to it. The event listener functions called are functions added to the $scope object by the controller function.

What are the top reasons why developers choose AngularJS?

Answer

AngularJS, an Open Source web application framework by Google, is widely used in building highly robust and scalable Single Page Applications (SPA). Single Page Applications are websites or web applications that encompass a single web page, rendering a seamless and immersive user experience. The framework is written in JavaScript, and allows using HTML as template language. It helps build rich and intuitive web applications, and also provides web developers the option to build client-side applications.

High Performance

AngularJS is a popular choice among web developers because of  ease of use and maintenance, intuitive features, robustness, and the efficiency to build new features. It is obvious that when a problem arises, developers are not ready to spend hours debugging it. At the same time, they should be able to make minor changes with much ease. AngularJS gives you the ease of maintenance.

Effective Handling of Dependencies

AngularJS does dependency injection extremely well. For Single Page Applications, Angular makes it extremely easy to organize things like dynamic loading and dependencies, and use them as required without worrying about “Did I spin up an instance?” or “What namespace does it live in?” Simply mention what you need, and Angular will get it for you and also manage the entire life-cycle of the objects.

For testing, the framework allows you to segregate the app into logical modules that may have dependencies on each other, but are separately initialized. This helps to take a tactical approach towards testing as it provides only the modules that you need. Now, since the dependencies are injected, you can have an existing service like Angular $HTTP and swap it easily with $httpBackend mock for effective testing.

DOM has Markup in AngularJS

In most client-side JavaScript frameworks, the temples operate in something like this way,

  • Template with markup -> framework template engine -> HTML -> DOM

    However, in AngularJS, the markup is directly put into the HTML document and flow looks something like this,

  • HTML with Angular markup -> DOM -> Angular Template Engine

    The framework evaluates the markup only when HTML has been loaded into DOM.

This has three major benefits – simplicity, integration with existing apps, and extensibility. You can work with AngularJS in basic HTML documents from a local file system. Additionally, it allows you to build custom attributes and elements that can extend the basic HTML vocabulary.

Explain $routeProvider in AngularJS?

Answer

The $routeProvider is used to set the configuration of urls and map them with the corresponding html page or ng-template and also attach a controller. Routing in AngularJS is taken care of by a service provide that is called $routeProvider. Routes for templates and urls in Angular are declared via the$routeProvider, that is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser.

We can use config() method of “myApp” module to configure $routeProvider. The when method of$routeProvideris used to bind the url with a template. This method takes a url(i.e. “/viewDelhi”) that will map with a template (i.e. delhi.htm) using the templateUrl parameter. The when method also binds a controller for templates using the controller parameter (i.e. controller: ‘AddDelhi’), otherwise the method is used to set the default view.

Example

  1. mainApp.config([‘$routeProvider’, function($routeProvider)
  2. {
  3.     $routeProvider.
  4.     when(‘/viewDelhi’,
  5.     {
  6.         templateUrl: ‘delhi’,
  7.         controller: ‘AddDelhi’
  8.     }).
  9.     when(‘/viewMumbai’,
  10.     {
  11.         templateUrl: ‘mumbai’,
  12.         controller: ‘AddMumbai’
  13.     }).
  14.     when(‘/viewJaipur’,
  15.     {
  16.         templateUrl: ‘jaipur’,
  17.         controller: ‘AddJaipur’
  18.     }).
  19.     otherwise
  20.     ({
  21.         redirectTo: ‘/viewDelhi’
  22.     });
  23. }]);

 

What are the attributes can be used during creation of a new AngularJS Directives?

Answer

The following attributes can be used during creation of a new AngularJS Directives,

  1. Restrict

    The restrict attribute is how AngularJS triggers the directive inside a template. The default value of the restrict option is “A”. The value of “A” causes the directives to be triggered on the attribute name. Other than “A”, restrict option has “E” (only match element name), “C” (only match class name) and “M” (only match the comment name) or any combination among four options.
  2. TemplateUrl

    The templateUrl attribute tells the AngularJS HTML compiler to replace custom directive inside a template with HTML content located inside a separate file. The link-Menu (say, our custom directive name) attribute will be replaced with the content of our original menu template file.
  3. Template

    Specify an inline template as a string. Not used if you’re specifying your template as a URL.

  4. Replace

    If true, replace the current element. If false or unspecified, append this directive to the current element.

  5. Transclude

    Lets you move the original children of a directive to a location inside the new template.

  6. Scope

    Create a new scope for this directive rather than inheriting the parent scope.

  7. Controller

    Create a controller which publishes an API for communicating across directives.

  8. Require

    Require that another directive be present for this directive to function correctly.

  9. Link

    Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

  10. Compile

    Programmatically modify the DOM template for features across copies of a directive, as when used in other directives. Your compile function can also return link functions to modify the resulting element instances.

Explain what is injector in AngularJS?

Answer

The $injector service is responsible for determining the dependencies that a function declares and resolving those dependencies. The below table lists the methods supported by the $injector service.

Name Descriptions
annotate(fn) Gets the arguments for the specified function, including those that do not correspond to services
get(name) Gets the service object for the specified service name
has(name) Returns true if a service exists for the specified name
invoke(fn, self, locals) Invoked the specified function, using the specified value for this and the specified non-service argument values.

The $injector service is right at the core of the AngularJS library, and there is rarely a need to work directly with it, but it can be useful for understanding and customizing how AngularJS works. However, these are the kind of customizations that should be considered carefully and tested thoroughly.

Getting the $injector Service from the Root Element

The $rootElement service provides access to the HTML element to which the ng-app directive is applied and which is the root of the AngularJS application. The $rootElement service is presented as a jqLite object, which means you can use jqLite to locate elements or modify the DOM using the jqLite methods I described in Chapter 15. Of interest in this chapter, the $rootElement service object has an additional method called injector, which returns the $injector service object. You can see how I replaced the dependency on the $injector service with the $rootElement service in the below example.

Index.html

  1. <!DOCTYPE html>
  2. <html xmlns=”http://www.w3.org/1999/xhtml” ng-app=”TestApp”>
  3. <head>
  4.     <title>Angular Injection</title>
  5.     <script src=”angular.js”></script>
  6.     <script src=”app.js”></script>
  7.     <script src=”Index.js”></script>
  8. </head>
  9. <body ng-controller=”indexController”>
  10.     <div class=”well”>
  11.         <button class=”btn btn-primary” ng-click=”handleClick()”>Click Me!</button>
  12.     </div>
  13. </body>
  14. </html>

Index.js

  1. testApp.controller(“indexController”, function($scope, $log, $rootElement)
  2.     var counter = 0;
  3.     var logClick = function($log, $exceptionHandler, message)
  4.     {
  5.         if (counter == 0)
  6.         {
  7.             $log.log(message);
  8.             counter++;
  9.         } else {
  10.             $exceptionHandler(“Already clicked”);
  11.         }
  12.     }
  13.     $scope.handleClick = function()
  14.     {
  15.         var localVars =
  16.         {
  17.             message: “Button Clicked”
  18.         };
  19.         $rootElement.injector().invoke(logClick, null, localVars);
  20.     };
  21. });

The output of the code is as below,
Mention what are the characteristics of “Scope”?

Answer

$scope is a glue between the View and the Controller. It connects a Controller with the View,

  1. $scope serves as the glue between the Controller and the View.
  2. The $scope is the connection between the HTML and the View.
  3. The View and the model both have access to the $scope.
  4. In the context of MVC, $scope can be seen as the ViewModel.
  5. $scope provides the execution context for the DOM and the expression.
  6. $scope provides an execution context in which the DOM element is bound.
  7. $scope is the source of the truth.
  8. $scope is modified when the View changes and the View is modified when $the scope changes its value.
  9. The $scope object is a plain JavaScript object. We can add and remove a property as required.
  10. $scope holds data and functions from the Controller that should be displayed and executed in the View.
  11. The $rootScope is the eventual parent of all the $scope.
  12. $rootScope is the top-most scope in a DOM element with the ng-app directive.
  13. In angular all the $scope are created with prototypal inheritance.
  14. $scope has access to their parent scope.
  15. $scope contains data and the functionality to be used to render the View.
  16. For each Controller created a new $scope is created.
  17. It is ideal to contain the application logic in the Controller and the data in the $scope of the Controller.
  18. When $the scope object is not needed in the View, the scope will be cleaned up and destroyed.
  19. Directives do not have their own scope but with some exceptions ng-controller and ng-repeat do.
  20. When angular starts running all the $scope are attached to the View.
  21. $scope passes data and behavior to the View.
  1. Give the differences between AngularJS and Backbone and Knockout?

    Answer

    Comparison with Backbone.js and Knockout.js,

Comparison AngularJs Backbone.js Knockout.js
File Size ~142 KB total (compressed and minified) ~ 7.3 KB total (gzip / minified) ~21 KB total (gzip / minified)
Version & Licence V1.4.2 & MIT (Open-source) V1.2.1 & MIT (Open-source) V3.3.0 & MIT (Open-source)
Dependencies No Dependencies Dependends on underscore.js and jQuery No Dependencies
Data Binding It supports full data binding and provides options for creating custom data bindings Does not support data binding by default but does using plugins for data bindings It fully supports data binding and can bind many attributes.
It provides options for creating custom data bindings
Routing It supports routing feature and it’s very simple It supports routing features and it’s very simple Does not support routing by defualt but it is available with some thrid-party libraries
Views Uses HTML as the templating language Does not have templates by default but we can add them easily by a thrid-party template like underscore.js and handlebars It uses HTML as the templating language
Testing Can support Test Driven Development (TDD) Does not support testing by defualt but we can use some thrid-party tester like Jasmine and Sinon.JS Does not support testing by defualt but we can use some thrid-party tester like Jasmine and Sinon.JS
Data Does not support jQuery but we can use Angular’s $http Can support jQuery’s $.ajax and is very easy to understand It can support jQuery’s $.ajax and knockout mapping
Design Pattern Can support the MVC and MVVM design patterns It can support MVP design pattern It can support the MVVM design pattern
Browser Can support IE 9, IE 10 and IE 11 It dependends on jQuery supporting browsers like IE 6+, Chrome, Firefox, Safari 5.1+ and Opera It can support all major browsers like IE 6+, Firefox 3.5+, Chrome, Opera and Safari
Third-party Integration Does not support third-party integration Does not support third-party integration It supports third-party integration
Documentation It has available documentation and community To my knowledge there is no documentation It has available documentation and community

 

What are the custom directives in AngularJS?

Answer

In AngularJS we can create the custom directive for the following types of elements.

Element directives Directive activates when a matching element is encountered. Restrict mode is defined by “E”.

Example <ng-directives></ng-directives>

Attribute Directive activates when a matching attribute is encountered. Restrict mode is defined by “A”.

Example <span ng-directive></span>

CSS Directive activates when a matching css style is encountered. Restrict mode is defined by “C”.

Example <span class=”ng-directive”></span>

Comment Directive activates when a matching comment is encountered. Restrict mode is defined by “M”.

Example <!– directive: ng-directive –>

Let us create some custom directives:

Now we read how to create custom directives. We start with some simple examples and move towards some complex custom directives.

Example 1

  1. <html>
  2. <head>
  3.     <title>Angular JS Example</title>
  4.     <script src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js”>
  5.     </script>
  6.     <style>
  7.         .sparkline
  8.         {
  9.             background-color: brown;
  10.             font-size: large;
  11.             height: 100px;
  12.             width: 200px;
  13.             color: aqua
  14.         }
  15.     </style>
  16. </head>
  17. <body>
  18.     <h2>AngularJS Custom Directive Example</h2>
  19.     <div ng-app=”mainApp”>
  20.         <divng-demo>
  21.     </div>
  22.     </div>
  23. </body>
  24. <script>
  25.     var mainApp = angular.module(“mainApp”, []);
  26.     mainApp.directive(‘ngDemo’, function() {
  27.         return
  28.         {
  29.             restrict: ‘A’,
  30.             template: ‘<div class=”sparkline”>This is simple Custom Directive of Element Type</div>’
  31.         }
  32.     });
  33. </script>
  34. </html>