What is Angular JS ?
{{ firstName }} is synchronized with ng-model="firstName".
AngularJS is 100% JavaScript, 100% client side and compatible with both desktop and mobile browsers. So it's definitely not a plugin or some other native browser extension.
What are the key features of AngularJS?
Scope
Scope refers to the application model, it acts like glue between application controller and the view. The job of the Scope is to detect changes to model objects and create an execution context for expressions. There is one root scope for the application (ng-app) with hierarchical children scopes. It marshals the model to the view and forwards events to the controller.
Actually it is a ViewModel. that works as a mediater between View and Controller to bind and View Data.
Controller
AJs controllers control the data of AngularJS Applications.they are like regular javascript object. The Controller is responsible for construction of the model and connects it to the view (HTML). The scope sits between the controller and the view. Controllers should be straightforward and simply contain the business logic needed for a view. Generally you want thin controllers and rich services. Controllers can be nested and handle inheritance. The big difference in AngularJS from the other JavaScript frameworks is there is no DOM manipulation in controllers. It is something to unlearn when developing in AngularJS.
Model
In AngularJS, a Model is simply a JavaScript object. No need to extend anything or create any structure. This allows for nested models - something that Backbone doesn’t do out-of-the-box.
View
The View is based on DOM objects, not on strings. The view is the HTML. HTML is declarative – well suited for UI design. The View should not contain any functional behavior. The flexibility here is to allow for multiple views per Controller.
Services
The Services in AngularJS are singletons that perform common tasks for web applications. If you need to share common functionality between Controllers, then use Services. Built-in AngularJS, Services start with a $. There are several ways to build a service: Service API, Factory API, or the $provide API.
Data Binding
Data Binding in AngularJS is a two-way binding between the View and the Model. Automatic synchronizing between views and data models makes this really easy (and straightforward) to use. Updating the model is reflected in View without any explicit JavaScript code to bind them together, or to add event listeners to reflect data changes.
Directives
AngularJS allows you to use Directives to transform the DOM or to create new behavior. A directive allows you to extend the HTML vocabulary in a declarative fashion. The ‘ng’ prefix stands for built-in AngularJS directives. The App (ng-app), Model (ng-model), the Controller (ng-controller), etc. are built into the framework. AngularJS allows for building your own directives. Building directives is not extremely difficult, but not easy either. There are different things that can be done with them. Please check out AngularJS’s documentation on directives.
Different types of directives are
Element directives
Attribute directives
CSS class directives
Comment directives
Filters
The Filters in AngularJS perform data transformation. They can be used to do formatting (like I did in my Directives example with padding zeros), or they can be used to do filter results (think search).
Validation
AngularJS has some built-in validation around HTML5 input variables (text, number, URL, email, radio, checkbox) and some directives (required, pattern, minlength, maxlength, min, max). If you want to create your own validation, it is just as simple as creating a directive to perform your validation.
Testable
Testing is a big concern for enterprise applications. There are several different ways to write and run tests against JavaScript code, thus against AngularJS. The developers at AngularJS advocate using Jasmine tests ran using Testacular. I have found this method of testing very straightforward and, while writing tests may not be the most enjoyable, it is just as importable as any other piece of developing an application.
What is a scope in AngularJS?
scope is an object that refers to the application model. It is the glue between application controller and the view. Both the controllers and directives have reference to the scope, but not with each other. It is an execution context for expressions and arranged in hierarchical structure. Scopes can watch expressions and propagate events.
What is Routing? How to Create it in AngularJS?
AngularJS routes enable you to create different URLs for different content in your application. for routing you have to include angular-route.min.js file.
If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate
module:
You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc.angular.module is used to configure the $injector.
Directives- are the attribute provided by the angularjs.
ex: ng-app, ng-init, ng-model, ng-bind
ng-init -> initialize application data.
ex:- ng-init="name='suraj'"
ng-model -> bind application data(model property) to html element.
ex:- ng-model="name"
ng-bind -> bind application variable name with html control.
ex:- ng-bind="name" . it's jst like expressions {{}}
AngularJS Expression - written inside double braces. {{name}}. it binds data to html the same way as the ng-bind directive.
How will you show/hide buttons and enable/disable buttons conditionally?
Using the ng-show and ng-disabled directives.
How will you loop through a collection and list each item?
Using the ng-repeat directive.
How to enable and disable buttons with using condition?
How to bind selection box with options in the angular js?
CountriesCitiesList.json is the next file used in $http.get('CountriesCitiesList.json') for display list.
[
How to display images based on the status(A, B, and C) in angular js?
Mention what are the advantages of using Angular.js framework ?
Advantages of using Angular.js as framework are
Supports two way data-binding
Supports MVC pattern
Support static template and angular template
Can add custom directive
Supports REST full services
Supports form validations
Support both client and server communication
Support dependency injection
Applying Animations
Event Handlers
What is Service?
the services are singleton objects or functions that carry out specific tasks. It holds some business logic.
What is The difference between factory and service in Angular JS ?
The difference between factory and service is just like the difference between a function and an object. The difference between the two is just the way in which they create the object that goes and gets the data. That’s really all two is to it.
(- With the factory you actually create an object inside of the factory and return it.
(- With the service you just have a standard function that uses the this keyword to define
function.
Click here to know more Click here
What is $Watch() ?
The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:
A value function
A listener function
Here is an example:
The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed. Here is an example:
What is $Digest() ?
The $scope.$digest() function iterates through all the watches in the $scope object, and its child $scope objects (if it has any). When $digest() iterates over the watches, it calls the value function for each watch. If the value returned by the value function is different than the value it returned the last time it was called, the listener function for that watch is called.
to know more about $watch and $digest click here
$q - A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.
angular.copy
Creates a deep copy of source, which should be an object or an array.
angular.copy(source, [destination]);
HTML <form> novalidate Attribute
When present, it specifies that the form-data (input) should not be validated when submitted.
<form novalidate>
ng-view
ng-view tag simply creates a place holder where a corresponding view (html or ng-template view) can be placed based on the configuration.
ng-template
ng-template directive is used to create an html view using script tag. It contains "id" attribute which is used by $routeProvider to map a view with a controller.
Usage
Define a script block with type as ng-template within the main module.
</div>
value
value is simple javascript object and it is used to pass values to controller during config phase.
constant
constants are used to pass values at config phase considering the fact that value can not be used to be passed during config phase.
Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object.
A deferred object is simply an object that exposes a promise as well as the associated methods for resolving that promise. It is constructed using the $q.deferred() function and exposes three main methods: resolve(), reject(), and notify(). The associated promise object can be accessed via the promise property.
What is Interpolation in AngularJS?
Interpolation is such a process when AngularJS fetches a calculated string into the text between HTML element tag and within attribute assignments.
Let's see example of interpolation:
In this example {{myImageUrl}} first is been evaluated by AngularJS and only then it converts it to a string. And remember that template expression cannot refer to anything in the global namespace.
$interpolate : This service is used to evaluate angular expressions. You can run an entire string against a scope, and interpolate will give the result.
e.g would be
AngularJS is an open-source javascript framework developed by Google. It helps us to create single-page application using html, javascript,css on client side. AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions. It is more testable , maintainable. It provides a new way to develop web application.
AngularJS extends HTML with ng-directives.
The ng-app directive defines and initialize an AngularJS application.it is the root element.
The ng-model directive binds element values (like the value of an input field) to the application.
The ng-bind directive binds application data to the HTML view.
The ng-model directive binds element values (like the value of an input field) to the application.
The ng-bind directive binds application data to the HTML view.
<!DOCTYPE html>
<html>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
<html>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
AngularJS starts automatically when the web page has loaded.
The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.
The ng-model directive binds the value of the input field to the application variable name.
The ng-bind directive binds application variable name to the innerHTML of a paragraph.
The ng-init directive initialize AngularJS application variables with data.
<div ng-app="" ng-init="firstName='John'">
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
Data binding in AngularJS, synchronizes AngularJS expressions with AngularJS data.
{{ firstName }} is synchronized with ng-model="firstName".
Is AngularJS a library, framework, plugin or a browser extension?
AngularJS fits the definition of a framework the best, even though it's much more lightweight than a typical framework and that's why many confuse it with a library.AngularJS is 100% JavaScript, 100% client side and compatible with both desktop and mobile browsers. So it's definitely not a plugin or some other native browser extension.
What are the key features of AngularJS?
Scope
Scope refers to the application model, it acts like glue between application controller and the view. The job of the Scope is to detect changes to model objects and create an execution context for expressions. There is one root scope for the application (ng-app) with hierarchical children scopes. It marshals the model to the view and forwards events to the controller.
Actually it is a ViewModel. that works as a mediater between View and Controller to bind and View Data.
Controller
AJs controllers control the data of AngularJS Applications.they are like regular javascript object. The Controller is responsible for construction of the model and connects it to the view (HTML). The scope sits between the controller and the view. Controllers should be straightforward and simply contain the business logic needed for a view. Generally you want thin controllers and rich services. Controllers can be nested and handle inheritance. The big difference in AngularJS from the other JavaScript frameworks is there is no DOM manipulation in controllers. It is something to unlearn when developing in AngularJS.
Model
In AngularJS, a Model is simply a JavaScript object. No need to extend anything or create any structure. This allows for nested models - something that Backbone doesn’t do out-of-the-box.
View
The View is based on DOM objects, not on strings. The view is the HTML. HTML is declarative – well suited for UI design. The View should not contain any functional behavior. The flexibility here is to allow for multiple views per Controller.
Services
The Services in AngularJS are singletons that perform common tasks for web applications. If you need to share common functionality between Controllers, then use Services. Built-in AngularJS, Services start with a $. There are several ways to build a service: Service API, Factory API, or the $provide API.
Data Binding
Data Binding in AngularJS is a two-way binding between the View and the Model. Automatic synchronizing between views and data models makes this really easy (and straightforward) to use. Updating the model is reflected in View without any explicit JavaScript code to bind them together, or to add event listeners to reflect data changes.
Directives
AngularJS allows you to use Directives to transform the DOM or to create new behavior. A directive allows you to extend the HTML vocabulary in a declarative fashion. The ‘ng’ prefix stands for built-in AngularJS directives. The App (ng-app), Model (ng-model), the Controller (ng-controller), etc. are built into the framework. AngularJS allows for building your own directives. Building directives is not extremely difficult, but not easy either. There are different things that can be done with them. Please check out AngularJS’s documentation on directives.
Different types of directives are
Element directives
Attribute directives
CSS class directives
Comment directives
Filters
The Filters in AngularJS perform data transformation. They can be used to do formatting (like I did in my Directives example with padding zeros), or they can be used to do filter results (think search).
Validation
AngularJS has some built-in validation around HTML5 input variables (text, number, URL, email, radio, checkbox) and some directives (required, pattern, minlength, maxlength, min, max). If you want to create your own validation, it is just as simple as creating a directive to perform your validation.
Testable
Testing is a big concern for enterprise applications. There are several different ways to write and run tests against JavaScript code, thus against AngularJS. The developers at AngularJS advocate using Jasmine tests ran using Testacular. I have found this method of testing very straightforward and, while writing tests may not be the most enjoyable, it is just as importable as any other piece of developing an application.
What is a scope in AngularJS?
scope is an object that refers to the application model. It is the glue between application controller and the view. Both the controllers and directives have reference to the scope, but not with each other. It is an execution context for expressions and arranged in hierarchical structure. Scopes can watch expressions and propagate events.
What is Routing? How to Create it in AngularJS?
AngularJS routes enable you to create different URLs for different content in your application. for routing you have to include angular-route.min.js file.
//
create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute']);
//
configure our routes
scotchApp.config(function ($routeProvider) {
$routeProvider
// route
for the home page
.when('/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
// route
for the about page
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
});
If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate
module:
var scotchApp = angular.module('scotchApp', ['ngRoute', 'ngAnimate']);
<div ng-app="" ng-init="quantity=1;cost=5">
What are the advantages of using Angular.js framework ?
Advantages of using Angular.js as framework are:
Supports two way data-binding
Supports MVC pattern
Support static template and angular template
Can add custom directive
Supports REST full services
Supports form validations
Support both client and server communication
Support dependency injection
Applying Animations
Event Handlers
Explain what are the key features of Angular.js?
Scope
Controller
Model
View
Services
Data Binding
Directives
Filters
Testable
What are the different types of Directive?
Different types of directives are
Element directives
Attribute directives
CSS class directives
Comment directives
Explain what is injector?
An injector is a service locator, used to retrieve object instances.
app.controller("AppCtrl", function ($scope, $injector) { $injector.invoke(function (game) { alert(game.title); $scope.title = game.title; }); });
https://thinkster.io/egghead/injectors
Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies ?
DI or Dependency Injection is a software design pattern that deals with how code gets hold of its dependencies.
What is the bootstrapping in AngularJS?
Ans: Bootstrapping in AngularJS is nothing but just initializing, or starting, your Angular app. AngularJS supports automatic bootstrapping as well as manual way as well.
There are two ways of bootstrapping AngularJS. One is Automatic Initialization and other is Manually using Script.
Another way to bootstrapping is manually initializing using script. Manual initialization provides you more control on how and when to initialize angular App. It is useful when you want to perform any other operation before Angular wakes up and compile the page. Below is the script which allows to manually bootstrap angularJS.
ng-app Directive: The ng-app directive is a starting point of AngularJS Application. It initializes the AngularJS framework automatically. AngularJS framework will first check for ng-app directive in a HTML document after the entire document is loaded and if ng-app is found, it bootstraps itself and compiles the HTML template.
What is Module? How to Create it in AngularJS?
AngularJS ExpressionsAngularJS binds data to HTML using Expressions.
AngularJS expressions are written inside double braces: {{ expression }}.
AngularJS expressions binds data to HTML the same way as the ng-bind directive.
AngularJS will "output" data exactly where the expression is written.
AngularJS expressions binds data to HTML the same way as the ng-bind directive.
AngularJS will "output" data exactly where the expression is written.
AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.
Example: {{ 5 + 5 }} or {{ firstName + " " + lastName }}
AngularJS Numbers
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div
Same example using ng-bind:
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>
AngularJS Strings
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is {{ firstName + " " + lastName }}</p>
</div>
Same example using ng-bind:
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
AngularJS Objects
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>
</div>
Same example using ng-bind:
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is <span ng-bind="person.lastName"></span></p>
</div>
AngularJS Arrays
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The points are {{ points[2] }}</p>
</div>
Same example using ng-bind:
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The points are <span ng-bind="points[2]"></span></p>
</div>
Repeating HTML Elements
The ng-repeat directive repeats an HTML element:
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
<div>
The ng-repeat directive used on an array of objects:
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
The Controller
The controller define the actual behavior of your app. It contains business logic for the view and connects the right models to the right views. A controller is associated with a HTML element with the ng-controller directive.
The $scope of the controller is the application /the HTML element) it is referred from.
<div ng-app="" ng-controller="personController">
First Name: <input type="text" ng-model="person.firstName"><br>
Last Name: <input type="text" ng-model="person.lastName"><br>
<br>
Full Name: {{person.firstName + " " + person.lastName}}
</div>
<script>
function personController($scope) {
$scope.person = {
firstName: "John",
lastName: "Doe"
};
}
</script>
Application explained:
The AngularJS application is defined by ng-app. The application runs inside a <div>.
The ng-controller directive names the controller object.
The function personController is a standard JavaScript object constructor.
The controller object has one property: $scope.person.
The person object has two properties: firstName and lastName.
The ng-model directives binds the input fields to the controller properties (firstName and lastName).
A controller can also have methods:
<div ng-app="" ng-controller="personController">
First Name: <input type="text" ng-model="person.firstName"><br>
Last Name: <input type="text" ng-model="person.lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
function personController($scope) {
$scope.person = {
firstName: "John",
lastName: "Doe",
};
$scope.fullName = function() {
var x;
x = $scope.person;
return x.firstName + " " + x.lastName;
};
}
</script>
AngularJS Filters
Filters are used to format data before displaying it to the user. There are some built-in filters provided by angularjs like as Currency, Date, Number, OrderBy, Lowercase, Uppercase etc. Filters can be added to expressions and directives using a pipe character. You can also create your own filters.
Syntax: {{ expression | filter}}
<div ng-app="" ng-controller="personController">
<p>The name is {{ person.lastName | uppercase }}</p>
</div>
The currency Filter
The currency filter formats a number as currency:
<div ng-app="" ng-controller="costController">
<input type="number" ng-model="quantity">
<input type="number" ng-model="price">
<p>Total = {{ (quantity * price) | currency }}</p>
</div>
Adding Filters to Directives
A filter can be added to a directive with a pipe character (|) and a filter.
The orderBy filter orders an array by an expression:
<div ng-app="" ng-controller="namesController">
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
<div>
Filtering Input
An input filter can be added to a directive with a pipe character (|) and filter followed by a colon and a model name.
The filter filter selects a subset of an array:
<div ng-app="" ng-controller="namesController">
<p><input type="text" ng-model="name"></p>
<ul>
<li ng-repeat="x in names | filter:name | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>
</div>
The ng-show directive hides or shows an HTML element.
<p ng-show="true">I am visible.</p>
<p ng-show=" hour < 12">I am visible.</p>
<p ng-show=" hour < 12">I am visible.</p>
The ng-disabled directive binds application data directly to the HTML disabled attribute.
<div ng-app="">
<p>
<button ng-disabled="mySwitch">Click Me!</button>
</p>
<p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
</div>
Application explained:
The ng-disabled directive binds the application data "mySwitch" to the HTML disabled attribute.
The ng-model directive binds "mySwitch" to the content (value) of the HTML input checkbox element.
The ng-click directive defines an AngularJS click event.
<div ng-app="" ng-controller="personController">
<button ng-click="toggle()">Toggle</button>
<p ng-show="myVar">
First Name: <input type="text" ng-model="person.firstName"><br>
Last Name: <input type="text" ng-model="person.lastName"><br>
<br>
Full Name: {{person.firstName + " " + person.lastName}}
</p>
</div>
<script>
function personController($scope) {
$scope.person = {
firstName: "John",
lastName: "Doe"
};
$scope.myVar = true;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
}
</script>
Application explained:
The first part of the personController is the same as in the chapter about controllers.
The application has a new default property: $scope.myVar = true;
The ng-show directive uses the variable myVar (true or false).
A new function toggle() toggles myVar between true and false.
What is $routeProvider?
$routeProvider is the key service which set the configuration of urls, map them with the corresponding html page or ng-template, and attach a controller with the same.
What is $routeProvider?
$routeProvider is the key service which set the configuration of urls, map them with the corresponding html page or ng-template, and attach a controller with the same.
AngularJS Modules
AngularJS modules divides your web application into small, reusable and functional components which can be
integrated with other web applications. Each module is identified by a unique name and can be dependent on
other modules.
Controllers Pollute the Global Namespace
All examples, so far in this tutorial, have used global functions.
Global variables and global functions should be avoided in all applications.
Global values (variables or functions) can be overwritten or destroyed by other scripts.
To solve this problem AngularJS uses modules.
Using a simple controller:
<body>
<div ng-app="" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
function myCtrl($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
Using a controller owned by a module instead:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
Where to Put Module Definitions
A common advise for HTML applications, is to place all scripts at the very bottom of the <body> element.
This improves page loading, because HTML loading is not blocked by scripts loading.
In many AngularJS examples, you will se the Angular library being loaded in the <head> of the document.
In the example above, AngularJS is loaded in the <head> element, because the call to angular.module can only be done after the library has been loaded.
Advantages of using Angular.js as framework are:
Supports two way data-binding
Supports MVC pattern
Support static template and angular template
Can add custom directive
Supports REST full services
Supports form validations
Support both client and server communication
Support dependency injection
Applying Animations
Event Handlers
Explain what are the key features of Angular.js?
Scope
Controller
Model
View
Services
Data Binding
Directives
Filters
Testable
What are the different types of Directive?
Different types of directives are
Element directives
Attribute directives
CSS class directives
Comment directives
Explain what is injector?
An injector is a service locator, used to retrieve object instances.
app.controller("AppCtrl", function ($scope, $injector) { $injector.invoke(function (game) { alert(game.title); $scope.title = game.title; }); });
https://thinkster.io/egghead/injectors
Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies ?
DI or Dependency Injection is a software design pattern that deals with how code gets hold of its dependencies.
What is the bootstrapping in AngularJS?
Ans: Bootstrapping in AngularJS is nothing but just initializing, or starting, your Angular app. AngularJS supports automatic bootstrapping as well as manual way as well.
There are two ways of bootstrapping AngularJS. One is Automatic Initialization and other is Manually using Script.
Another way to bootstrapping is manually initializing using script. Manual initialization provides you more control on how and when to initialize angular App. It is useful when you want to perform any other operation before Angular wakes up and compile the page. Below is the script which allows to manually bootstrap angularJS.
1 | <script> |
2 | angular.element(document).ready( function () { |
3 | angular.bootstrap(document, [ 'myApp' ]); |
4 | }); |
5 | </script> |
ng-app Directive: The ng-app directive is a starting point of AngularJS Application. It initializes the AngularJS framework automatically. AngularJS framework will first check for ng-app directive in a HTML document after the entire document is loaded and if ng-app is found, it bootstraps itself and compiles the HTML template.
You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc.angular.module is used to configure the $injector.
//
declare a module
var myAppModule = angular.module('myApp', []);
Directives- are the attribute provided by the angularjs.
ex: ng-app, ng-init, ng-model, ng-bind
ng-init -> initialize application data.
ex:- ng-init="name='suraj'"
ng-model -> bind application data(model property) to html element.
ex:- ng-model="name"
ng-bind -> bind application variable name with html control.
ex:- ng-bind="name" . it's jst like expressions {{}}
AngularJS Expression - written inside double braces. {{name}}. it binds data to html the same way as the ng-bind directive.
How will you show/hide buttons and enable/disable buttons conditionally?
Using the ng-show and ng-disabled directives.
<div class="dataControlPanel" ng-show="accounts.releasePortfolios"> <div class="dataControlButtons"> <button class="btn btn-primary btn-small" ng-click="saveComments()" ng-disabled="disableSaveButton"> Save </button> <button class="btn btn-primary btn-small" ng-click="releaseRun()" ng-disabled="disableReleaseButton"> Release </button> </div> </div>
How will you loop through a collection and list each item?
Using the ng-repeat directive.
<table class="table table-bordered table-striped table-hover table-fixed-head portal-data-table"> <thead> <tr> <th>account</th> <th>Difference</th> <th>Status</th> </tr> </thead> <tbody> <tr ng-repeat="account in acounts"> <td width="40%">{{account.accountCode}}</td> <td width="30%" style="text-align: right">{{account.difference | currency: ""}}</td> <td width="30%"> <div ng-switch on="account.status"> <div ng-switch-when="AMBER"> <img class="statusIcon" src='apps/dashboard/amber-dot.jpg' /> </div> <div ng-switch-when="GREEN"> <img class="statusIcon" src='apps/dashboard/green-dot.jpg' /> </div> <div ng-switch-when="RED"> <img class="statusIcon" src='apps/dashboard/red-dot.jpg' /> </div> </div> </td> </tr> </tbody> </table>
How to enable and disable buttons with using condition?
<div ng-app="myapp"> <div ng-controller="myScope"> First Name : <input type="text" ng-model="fName" /><br> Last Name : <input type="text" ng-model="lName" /><br> <button ng-disabled="!fName || !lName">Submit</button> </div> </div> <script> var $scope; var app = angular.module('myapp', []); function myScope($scope) { } </script>
How to bind selection box with options in the angular js?
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script> </head> <script> angular.module('SelectBoxWithOptions', []) .controller('Controller', ['$scope', '$http', function ($scope, $http) { $http.get('CountriesCitiesList.json') .success(function (data, status, headers, config) { $scope.locations = data; }); }]); </script> <body data-ng-app="SelectBoxWithOptions"> <h1>Select box with options</h1> <div class="ng-controller" data-ng-controller="Controller"> <label>Countries</label> <select data-ng-model="countries" data-ng-options="loc.country for loc in locations"> <option value="">Please chose country</option> </select> <label>Cities</label> <select data-ng-model='city' data-ng-options='c for c in countries.cities'> <option value="">Please chose city</option> </select> </div> </body> </html>
CountriesCitiesList.json is the next file used in $http.get('CountriesCitiesList.json') for display list.
[
{
"code": 1,
"country": "Germany",
"cities": [
"Berlin",
"Munich"
]
},
{
"code": 2,
"country": "Italy",
"cities": [
"Rome",
"Venice"
]
},
{
"code": 3,
"country": "United Kingdom",
"cities": [
"London",
"Manchester"
]
}
]
How to display images based on the status(A, B, and C) in angular js?
<div ng-switch on="account.status">
<div ng-switch-when="A">
<img class="statusIcon" src='apps/index/Adot.png' />
</div>
<div ng-switch-when="B">
<img class="statusIcon" src='apps/index/Bdot.png' />
</div>
<div ng-switch-when="C">
<img class="statusIcon" src='apps/index/Cdot.png' />
</div>
</div>
Mention what are the advantages of using Angular.js framework ?
Advantages of using Angular.js as framework are
Supports two way data-binding
Supports MVC pattern
Support static template and angular template
Can add custom directive
Supports REST full services
Supports form validations
Support both client and server communication
Support dependency injection
Applying Animations
Event Handlers
What is Service?
the services are singleton objects or functions that carry out specific tasks. It holds some business logic.
What is The difference between factory and service in Angular JS ?
The difference between factory and service is just like the difference between a function and an object. The difference between the two is just the way in which they create the object that goes and gets the data. That’s really all two is to it.
(- With the factory you actually create an object inside of the factory and return it.
(- With the service you just have a standard function that uses the this keyword to define
function.
Click here to know more Click here
What is $Watch() ?
The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:
A value function
A listener function
Here is an example:
$scope.$watch(function() {}, function() {} );The first function is the value function and the second function is the listener function.
The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed. Here is an example:
$scope.$watch(function(scope) { return scope.data.myVar }, function() {} );This example valule function returns the $scope variable scope.data.myVar. If the value of this variable changes, a different value will be returned, and AngularJS will call the listener function.
What is $Digest() ?
The $scope.$digest() function iterates through all the watches in the $scope object, and its child $scope objects (if it has any). When $digest() iterates over the watches, it calls the value function for each watch. If the value returned by the value function is different than the value it returned the last time it was called, the listener function for that watch is called.
to know more about $watch and $digest click here
$q - A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.
angular.copy
Creates a deep copy of source, which should be an object or an array.
- If no destination is supplied, a copy of the object or array is created.
- If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.
- If source is not an object or array (inc. null and undefined), source is returned.
- If source is identical to 'destination' an exception will be thrown.
angular.copy(source, [destination]);
$scope.update
= function
(user) {
//
Example with 1 argument
$scope.master = angular.copy(user);
};
$scope.reset
= function
() {
//
Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
AngularJS AJAX - $http
$http is an AngularJS service for reading data from remote servers.
The AngularJS $http service makes a request to the server, and returns a response.
$http({
url: _baseUrl + "/Home/FHDetail",
method: "GET",
params: { SearchId: sessionID, HotelCode: HCde }
}).success(function (data) {
$scope.SeacrhHotel = eval(data);
$scope.isCallPopupProgress = false;
}).error(function () {
debugger;
window.location = _baseUrl + '/Home/SessionExpired';
});
ngPluralize
This is used to display formatted data based on condition.
<ng-pluralize count="500" when="{0:'
child(2-11)',1:' child(2-11)', other: ' children(2-11)'}"></ng-pluralize>
Read in detail
Read in detail
Split Value in AngularJS Html
I have a Variable to split
To Split date value in Angular Js first you need to create a function in scope
$scope.date = "Thu 1 Sep 16";
$scope.SplittedValue = function (text, splitChar,
index) {
var array = text.split(splitChar);
return array[index];
}
In Html use like this
{{SplittedValue(date ,' ',0)}}
Difference between $scope and $rootscope
"$rootScope” is a parent object of all “$scope” angular objects created in a web page. $scope is created with ng-controller while $rootscope is created with ng-app . According to Angular's Developer's Guide to Scopes: Each Angular application has exactly one root scope, but may have several child scopes.
The "use strict" Directive
The purpose of "use strict" is to indicate that the code should be executed in "strict mode".
Why Strict Mode?
Strict mode makes it easier to write "secure" JavaScript.
Strict mode changes previously accepted "bad syntax" into real errors.
As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.
"$rootScope” is a parent object of all “$scope” angular objects created in a web page. $scope is created with ng-controller while $rootscope is created with ng-app . According to Angular's Developer's Guide to Scopes: Each Angular application has exactly one root scope, but may have several child scopes.
The "use strict" Directive
The purpose of "use strict" is to indicate that the code should be executed in "strict mode".
x = 3.14; // This will not cause an error.
myFunction();
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}
Why Strict Mode?
Strict mode makes it easier to write "secure" JavaScript.
Strict mode changes previously accepted "bad syntax" into real errors.
As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.
observe & watch
$watch is a method on the scope object which is
used to watch expressions. The expression can be either strings or functions.
$observe is a method on the attrs object which
is only used to observe the value change of a DOM attribute. It is only used
inside directives.
What is Angular Prefixes $ and $$?
AngularJS represents all public objects with $
and all private objects with $$. Its just a way of representing public and
private objects. This will avoid complication and help clear representation.
link function (Custom Directive)
link function is basically used to manipulate the DOM( Document Object Model ) element using custom directive. link option in custom directive registers DOM listener and also update the DOM. Click here for more
Config and Run in module
Configuration block - config() block is used to inject only providers and constants in our AngularJS application.
This block executed in AngularJS application during the provider registrations and configuration phase.
Now we have several types of providers in our AngularJS application. But if we want to use these provider first we need to inject these providers in our application with the help of config() block.
The providers basically create new instances, but only once for each provider.
Look at the following provider, which we can use in our application:
1.) $httpProvider
2.) $locationProvider
3.) $routeProvider
4.) $provider
5.) User defined Provider
6.) Constant
This block executed in AngularJS application during the provider registrations and configuration phase.
Now we have several types of providers in our AngularJS application. But if we want to use these provider first we need to inject these providers in our application with the help of config() block.
The providers basically create new instances, but only once for each provider.
Look at the following provider, which we can use in our application:
1.) $httpProvider
2.) $locationProvider
3.) $routeProvider
4.) $provider
5.) User defined Provider
6.) Constant
angular.module('crazydeveloperModule', []) .config(['$httpProvider','$locationProvider','$routeProvider','$provider','cookieProvider','constant', function ($httpProvider,$locationProvider,$routeProvider,$provider,cookieProvider,constant) { // provider-injector // This is an example of config block. // You can have as many of these as you want. // You can only inject Providers (not instances) // into config blocks. }])
Run block - This block is executed after the configuration block. It is used to inject instances and constants. This block is created using run() method. This method is like as main method in C or C++. The run block is a great place to put event handlers that need to be executed at the root level for the application. For example, authentication handlers.
angular.module('myModule', []) . run(['$rootscope','security','pageFactory','$httpBackend', function ($rootscope,security,pageFactory,$httpBackend) { // instance-injector // This is an example of a run block. // You can have as many of these as you want. // You can only inject instances (not Providers) // into run blocks }]);
HTML <form> novalidate Attribute
When present, it specifies that the form-data (input) should not be validated when submitted.
<form novalidate>
ng-view
ng-view tag simply creates a place holder where a corresponding view (html or ng-template view) can be placed based on the configuration.
<div ng-app = "mainApp">
...
<div ng-view></div>
</div>
ng-template
ng-template directive is used to create an html view using script tag. It contains "id" attribute which is used by $routeProvider to map a view with a controller.
Usage
Define a script block with type as ng-template within the main module.
<div ng-app = "mainApp">
...
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
value
value is simple javascript object and it is used to pass values to controller during config phase.
//define a module
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...
//inject the value in the controller using its name "defaultInput"
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
constant
constants are used to pass values at config phase considering the fact that value can not be used to be passed during config phase.
mainApp.constant("configParam", "constant value");
Difference:
Difference:
1) constant's value can not be change 2) value's data can be change
2) constant can be injected any where 2) value can be injected in controller, service, factory but can't be injected in config.
sample
var app = angular.module('app', []);
app.value('greeting', 'Hello');
app.config(function(greeting){
var radius = 4;
//PI can be injected here in the config block
var perimeter = 2 * PI * radius;
});
the above code will give error because trying to inject value into config.
A deferred object is simply an object that exposes a promise as well as the associated methods for resolving that promise. It is constructed using the $q.deferred() function and exposes three main methods: resolve(), reject(), and notify(). The associated promise object can be accessed via the promise property.
What is Interpolation in AngularJS?
Interpolation is such a process when AngularJS fetches a calculated string into the text between HTML element tag and within attribute assignments.
Let's see example of interpolation:
<h3> {{title}} <img src = "{{myImageUrl}}" > </h3>
In this example {{myImageUrl}} first is been evaluated by AngularJS and only then it converts it to a string. And remember that template expression cannot refer to anything in the global namespace.
e.g would be
var string = 'My Name is {{name}}';
$scope.name = 'Manish';
$interpolate(string)($scope); //this will result in My Name is Manish
transclude : transclusion is simply the method by which a directive displays content that was replaced by a directive’s template.
HTML Code
<div foo>Some Content Here</div>
JavaScript Code
.directive("foo", function() {// returns the Directive Definition Objectreturn {transclude: true,template: "<div>the template</div><div ng-transclude></div>"};})
The result of the using the ngTransclude directive is the following HTML output.
HTML Code
<div foo><div>the template</div><div ng-transclude>Some Content Here</div></div>
Observe that the original content of the DIV element has now been loaded into the content area of the DIV element on which the ngTransclude directive was placed. As you can see, transclusion is actually a pretty straightforward concept. https://www.accelebrate.com/
One more Important Link is here: http://www.toptal.com/angular-js/interview-questions
ReplyDeleteVery good collection of questions.It will surely helpful to many students and developers.
ReplyDeleteAngularJs Training
Hii author nice post! AngularJs is the best framework which is supported by google! I have personally used angularJs for my previous web app developement project and I'am quite satisfied by the output.
ReplyDeleteAngulars training | Angularjs training in Chennai | AngularJs training institute in Chennai
This post will be very useful to us....i like your blog and helpful to me....nice thoughts for your great work....
ReplyDeleteHire Angular Developers
Nice blog. Very informative. Thanks for sharing. Keep updating.
ReplyDeleteAngular js online training
Angular js online course
Angular js Online Training in Hyderabad
Angular js Online Training in Bangalore
Angular js Online Training in Chennai