Angular Js Interview Questions
Angular Js Interview Questions
Angular Js Interview Questions
* The root directive in angularjs is ng-app. We declare this directive in the root element of
the main html document(index.html)
*ng-app is called root directive because the angular framework starts execution of the
application from ng-app. And this process is called Autobootstrap`
*We can run the angular application with out ng-app through manual bootstrap
Manual bootstrap: Execution of the Angular application forcefully with out ng-app is called
Manual bootstrap....
*Sample code to run the application by using manual bootstrap i.e without using ng-app
<html>
</html>
Manualbootstrap.js
angular.element(document).ready(function(response){
angular.bootstrap(document.getElementById(“myh2”),[“app”]);
});
In the abovee code where there is ng-app scope that will be executed using auto bootstrap
that is h1 element
Note: we can use any number of ng-app in the application.. as the application is divided in
to number of modules so we can integrate every modules by creating one more new
project each having a ng-app shown below
Example:
In app.js file
Angular js is a Javascript framework to create Rich Internet Applications and the application
written in angularjs are cross browser compatible i.e., executes on any major web browser.
Scope: These are objects that refer to the model. They act as a glue between controller and
view.
Services − AngularJS has several built-in services for example $https which is used to make
requests using some url and fetch the required data.. These services creates the objects
only once and this object is shared to all the controllers.. so they are called singleton
objects which are instantiated only once in app.
Example: currency Format a number to a currency format. date Format a date to a specified
format. filter Select a subset of items from an array. json Format an object to a JSON string...
These select a subset of items from an array and returns a new array
pre -defined directives: These are built in directives provided by the angular frame work
ex: ng-model, ng-bind, ng-repeat etc
custom directives: creating our own directives based on application requirement called as
custom directives
Templates − These are the rendered view with information from the controller and model.
These can be a single file (like index.html) or multiple views in one page using "partials"
Deep Linking − 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.
Dependency Injection − AngularJS has a built-in dependency injection subsystem that helps
the developer by making the application easier to develop, understand, and test.
It is a root directory in
angularJS ,Framework will Ex: <html ng-app=”app”>
1,ng-app start the execution from
ng-app.
Loading the Target Templates to the Source Templates without refreshing is called as
Routing in Single Page Application
ngRoute Module: The ngRoute Module routes your application to different pages without
reloading the entire application.
bower.json-
dependencies:{
"angular":"~1.5.0",
"angular-route":"~1.5.0"
}
bower.json -
dependencies:{
"angular":"~1.6.0",
"angular-ui-router":"~0.2.18"
5. What is MVC?
MVC is a design pattern used to isolate business logic from presentation.
The MVC pattern has been given importance by many developers as a useful pattern for the
reuse of object code and a pattern that allows them to reduce the time it takes to develop
applications with user interfaces.
The Model-View-Controller (MVC) is an architectural pattern that separates an application
into three main logical components: the model, the view, and the controller. Each of these
components are built to handle specific development aspects of an application. MVC is one
of the most frequently used industry-standard web development framework to create
scalable and extensible projects.
MVC Components
Model: The Model component corresponds to all the data related logic that the user works
with. This can represent either the data that is being transferred between the View and
Controller components or any other business logic related data. For example, a Customer
object will retrieve the customer information from the database, manipulate it and update
it data back to the database or use it to render data.
View: The View component is used for all the UI logic of the application. For example, the
Customer view would include all the UI components such as text boxes, dropdowns, etc.
that the final user interacts with.
Controller: Controllers act as an interface between Model and View components to process
all the business logic and incoming requests, manipulate data using the Model component
and interact with the Views to render the final output. For example, the Customer
controller would handle all the interactions and inputs from the Customer View and update
the database using the Customer Model. The same controller would be used to view the
Customer data.
6. Ng-init directive
-> ng-init directive is used to intialize the application data Statically.
-> ng-init directive is used to define a local variable with value.
-> It is supported by all html elements.
Example:
<div ng-app="app "
ng-init="name='naresh it' ">
<h1>{ { name } } </h1>
</div>
->Each angular application has exactly one rootscope, but may have several child scopes.
->The s$cope will be available only inside the controller. But we can access $rootscope in all
the controllers.
8. What is Internationalization
Internationalization is the process of developing products in such a way that they can be
localized for languages and cultures easily. Localization (l10n), is the process of adapting
applications and text to enable their usability in a particular cultural or linguistic market.
--->that brings i18n (internationalization) and l10n (localization) into your Angular app.
--->It allows you to create a JSON file that represents translation data as per language.
example:
<html>
<head>
<title>Angular JS Forms</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<!-- <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-
dk.js"></script> -->
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('StudentController', function($scope) {
$scope.fees = 100;
$scope.admissiondate = new Date();
$scope.rollno = 123.45;
});
</script>
</body>
</html>
output:
AngularJS Sample Application
$100.00
Feb 27, 2017
123.45
The data binding is the data synchronization processes between the model and view
components
In angularjs when model data got changed that time the view data will change
automatically and vice versa.
We have two types of data bindings available in angularjs those are
1. One-Way data binding
2. Two-Way data binding
11 -2 Same Questions.
We will see simple example of using one way data binding in angularjs.
With the ng-model directive you can bind the value of an input field to a variable created in
AngularJS.
Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
AngularJS Controllers
AngularJS Example
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
15. $watch will watch changes which are done within the scope
The AngularJS $watch is used to observe properties on a single object and notify you if one of
them changes.
In other word watch is shallow watches the properties of an object and fires whenever any of
the properties change.
This method has callback function which gets called when the watching properties are
changed.
example:
<!doctype html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script>
var app=angular.module("app",[]);
app.controller("ctrl",ctrl);
ctrl.$inject=["$scope"]
function ctrl($scope){
$scope.$watch("expression",function(
newValue,oldValue,scope ){
console.log("newValue="+ newValue);
console.log("oldValue="+ oldValue);
console.log(scope.expression);
});
</script>
</html>
$eval:
The AngularJS $eval method is used to executes the AngularJS expression on the current
scope and returns the result.
In AngularJS, expressions are similar to JavaScript code snippets that are usually placed in
bindings such as {{ expression }}.
The important difference between $eval and $parse is that $eval is a scope
method that executes an expression on the current scope,
while $parse is a globally available service. The $eval method takes AngularJS expression and
local variable object as parameter.
$eval takes an angular expression, evaluates it and returns the actual result of that
expression.
for example1:
$scope.a = 2;
// result is 4
example2:
<!DOCTYPE html>
<script src="bower_components/angular/angular.min.js"></script>
<div>
<h1>a={{a}}</h1><br>
<h1>b={{b}}</h1><br>
<h1>Result={{a * b}}</h1>
</div>
<script>
var app=angular.module("app",[]);
app.controller("ctrl",ctrl);
ctrl.$inject=["$scope"];
function ctrl($scope) {
$scope.a = 10;
$scope.b = 20;
$scope.emp={
ename:"rk",age:24
};
$scope.clickMe = function () {
var r = $scope.$eval("a*b")
alert("result:" + r);
var r2=$scope.$eval("emp.ename");
alert(r2);
var r3=$scope.$eval("a*b*3");
alert(r3);
var r4=$scope.$eval("a*b*3*c");
alert(r4);
var r5=$scope.$eval("a*b*3*c",{c:5});
alert(r5);
var r6=$scope.$eval("a*b*3*c",{a:2,c:5});
alert(r6);
var r=$scope.$eval(function($scope,locals){
return $scope.a*$scope.b
})
alert(r);
var r=$scope.$eval(function($scope,locals){
return $scope.a*$scope.b*locals.c},
{a:2,b:3,c:6});
alert(r);
};
</script>
</html>
$parse:
$parse does not require scope. It takes an expression as a parameter and returns a function.
The function can be invoked with an object that can resolve the locals:
$parse takes an angular expression and returns a function that represents that expression.
For example1:
var fn = $parse('1+1+a');
// result is 4
example2:
<!DOCTYPE html>
<script src="bower_components/angular/angular.min.js"></script>
<div>
<h1>a={{a}}</h1><br>
<h1>b={{b}}</h1><br>
<h1>Result={{a * b}}</h1>
{{emp.ename}}
</div>
<button ng-click="clickMe()">parseDemo </button>
<script>
var app=angular.module("app",[]);
app.controller("ctrl",ctrl);
ctrl.$inject=["$scope","$parse"];
function ctrl($scope,$parse) {
$scope.a = 10;
$scope.b = 20;
$scope.emp = {
};
$scope.clickMe = function () {
// var r = my_fun($scope);
// alert("result=" + r);
//alert("result="+ $parse("a*b")($scope)
// alert("result="+ $parse("a*b")({a:2,b:3}));
// var r1 = my_fun($scope);
// alert("result=" + r1);
// var r2=my_fun({a:2,b:3});
// alert("result=" + r2);
// alert($parse("emp.ename")($scope));
($parse("emp.ename").assign($scope,"satti"));
// alert($parse("emp.ename")($scope));
}
}
</script>
The scope is the binding part between the HTML (view) and the JavaScript (controller).
The scope is available for both the view and the controller.
When you make a controller in AngularJS, you pass the $scope object as an argument:
Example:
<h1>{{carname}}</h1>
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
</script>
When adding properties to the $scope object in the controller, the view (HTML) gets
access to these properties.
In the view, you do not use the prefix $scope, you just refer to a propertyname, like
{{carname}}.
The scope is a JavaScript object with properties and methods, which are available for both
the view and the controller.
Example:
If you make changes in the view, the model and the controller will be updated:
<input ng-model="name">
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.name = "Ramakrishna";
});
</script>
I'm using Angular to develop commenting functionality for a web app. Currently there are
two sections in the application were a user can comment:
Category
Product
About 90% of the commenting functionality is the same for both sections and as such I would
like to make this reusable - i.e write some service or controller that I can reference/use as a
base.
So far, my research seems to point to using a factory service but unfortunately this doesn't
seem to work (I've spent the whole day running through various tutorials).
It is quite possible that I am over thinking this and making it far too complicated but I
honestly don't know which way to turn anymore.
Controller for the category (receives data from service and posts data to service in order to
bind data to model)
Service for the category (retrieve and stores all the necessary data)
The product uses the same logic and a lot of the code in the service and controller will be
duplicated. I've merged the two services into one service successfully but I'm having trouble
doing the same for the controller.
Do I:
Write a base controller that will communicate with the above mentioned service and that will
hookup with the two existing controllers
OR
Write a factory/provider service that hooks up to the two existing controllers as well as the
above mentioned service.
19. in our programming we are writing service as function that is that is to achieve
reusability
$observe() is a method on the Attributes object, and as such, it can only be used to
observe/watch the value change of a DOM attribute.
It is only used/called inside directives. Use $observe when you need to observe/watch a
DOM attribute that contains interpolation (i.e., {{}}'s).
(If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get
undefined.) Use $watch for everything else.
$watch() is more complicated. It can observe/watch an "expression", where the expression
can be either a function or a string.
(It is this function that is called every digest cycle.) The string expression can not contain
{{}}'s.
$watch is a method on the Scope object, so it can be used/called wherever you have access
to a scope object, hence in
Because strings are evaluated as Angular expressions, $watch is often used when you want
to observe/watch a model/scope property.
(If you try attrs.$observe('attr1') you'll get the string myModel.some_prop, which is
probably not what you want.)
As discussed in comments on @PrimosK's answer, all $observes and $watches are checked
every digest cycle.
Directives with isolate scopes are more complicated. If the '@' syntax is used, you can
$observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s).
(The reason it works with $watch is because the '@' syntax does the interpolation for us,
hence $watch sees a string without {{}}'s.)
To make it easier to remember which to use when, I suggest using $observe for this case
also.
To help test all of this, I wrote a Plunker that defines two directives. One (d1) does not
create a new scope, the other (d2) creates an isolate scope.
Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.
attr5="a_string" attr6="{{1+aNumber}}"></div>
Look at the console log to see the differences between $observe and $watch in the linking
function.
Then click the link and see which $observes and $watches are triggered by the property
changes made by the click handler.
Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated
yet (so if you try to examine the attributes, you'll get undefined).
The only way to see the interpolated values is to use $observe (or $watch if using an isolate
scope with '@').
value : is always a string reference to the watched element (the name of a scope's variable
or the name of the directive's attribute to be watched)
Therefore, getting the values of these attributes is an asynchronous operation. (And this is
why we need the $observe and $watch functions.)
1. Creating your own directive Based on 1. Loading the target templates without
application requirement is called custom refreshing web page is called as routing in
directive. single page application.
3. Here we don’t need any objects or 3. Here we need to pass objects to use the
services to use above levels. services like$route Provider, $state provider.
Custom directive scenario:Instead of coding common part in every view. Let’s create a
separate html file for common part and declare it as custom directive, then use it as custom
directive in every html file which Leads to less time consuming, better understanding,
increases reusability.22. List at least three ways to communicate between modules of your
application using angular js functionality?
A module can be injected into another module, in which case the container module has
access to all elements of the injected module. If you look at angular seed project, modules
are created for directive, controllers, filters etc, something like this
The second option is would be to use services. Since services are singleton and can be
injected into any controller, they can act as a communication mechanism.
Third option is to use parent controller using $scope object as it is available to all child
controllers.
You can also inject $rootScope into controllers that need to interact and use the $broadcast
and $on methods to create a service bus pattern where controllers interact using pub\sub
mechanism.
23. Different types of errors in Angular js? Can we do or create custom errors?
A. Errors:
Name Description
Name Description
nopromise No promise
Name Description
Name Description
$error: Is an object hash, containing references to all invalid controls or forms, where:
values are arrays of controls or forms that are invalid with given error.
24. what is the difference between ngshow and ngif and Ng hide?
ng-Show/nghide
--------------
===>The ng-show directive shows the specified HTML element if the expression
==>ngShow/ngHide work with the show and hide events that are triggered when the
directive expression is true and false in Animations
==>The great part about these directives is that "we don’t have to do any of the showing or
hiding ourselves with CSS or JavaScript".
==>Both ng-show and ng-if receive a condition and hide from view the directive’s element
==>ng-show (and its sibling ng-hide) toggle the appearance of the element by
==>The ng-hide directive hides the HTML element if the expression evaluates to true.
==>ng-hide is also a predefined CSS class in AngularJS, and sets the element's display to
none.
Syntax:
------
<element ng-show="expression"></element>
Parameter:
---------
Value Description
----- -----------
expression An expression that will show the element only if the expression returns true.
Example:
-------
<!DOCTYPE html>
<html>
<body ng-app="">
<div ng-show="myVar">
<h1>Welcome</h1>
</div>
</body>
</html>
25. How to implement securities in angular js? And what do u mean by IAutho?
Security
--------
==>Angular is not made to enhance security of our web application but to help
==>Do not run user input through $scope.$eval (or any of the other expression parsing
functions)
==>You can not access a angular variable/scope from console of your browser .
==>NG-CSP directive is given in angular to stop injecting inline codes to the application.
==>you have to send every http using ajax and you need to have an api for the back-end.
==>When developers build client apps with server back ends they approach the application
==>Assumptions are often made that the client they built will only ever talk to the server
side APIs
==>HTTP Requests, Whenever your application makes requests to a server there are
potential security
==>Using Local Caches, There are various places that the browser can store (or cache) data.
These objects, such as $templateCache are used to store and retrieve data,
==>primarily used by $http and the script directive to cache templates and other data.
==>Similarly the browser itself offers localStorage and sessionStorage objects for caching
data.
==>Attackers with local access can retrieve sensitive data from this cache even when users
are not authenticated.
For instance in a long running Single Page Application (SPA), one user may "log out",
but then another user may access the application without refreshing,
AngularJs is a client side UI frame work and also Client side JavaScript
Framework for building Dynamic web application,it fallows MVC(Model View
Controller)pattern.
It has set of ready to use modules to simplify building of Single Page
Applications.
Not security
Difficult to understanding the Angular Application because of no coding
standards given by venders
Client should enable the JavaScript then only you can run the Angular
Applications
More than 2000 watchers can severely lag the UI. That limits the complexity
Advantages of angularjs
Global community support is one of the factors, that can easily make Angular the
best javascript framework. Developers and designers constantly collaborate and
contribute to the community, increasing credibility and reliability of the framework.
Two-way data bind is probably the top feature, as it diffuses the impact after every
minor data change and does way with the need for further effort with data sync in view
and model.
Given the fact that our company makes active use of ng2, it is essential to include react vs
angular 2 comparison as well.
Advantages of reactjs
JSX is a JS syntax that enables HTML quotes and usage of HTML tag syntax for
subcomponents rendering. It promotes building of machine-readable code and provides
ability to compound components in one compile-time verified file.
Prompt rendering is among the best features of React that gives a significant edge
over Angular. The technology comprises smart methods to mitigate the amount of DOM
operations, optimize and accelerate the updates process. Virtual DOM (Document
Object Model) is of great use while handling vast databases.
The core difference between reactjs and angularjs is that React is JS-centric, while
ng2 remains HTML-centric. JavaScript is far more robust, than HTML, that makes React
far more simple, focused and consistent.
Disadvantages of angularjs
Disadvantages of react.js
Comparing react vs angular performance, first of all it’s worth mentioning that reactJS
is not a full-scale framework and for this very reason integration of the UI library into a
common MVC framework requires deeper programming knowledge. It is still young and
not mature, considering tutorial volumes, limited ecosystem, etc.
Apart from pros and cons of reactjs, we should also mention Flux that is frequently
applied for adding a structure and architecture to react app. Usage of both technologies
can become a challenge for non-experienced programmer, as it lacks structured and
comprehensive documentation or guide.
Conclusion
React and Angular offer completely diverse approaches to web application development for
startup, small and midmarket businesses. Both technologies are powerful and flexible, while
none of them is worse or better, than the other. Depending upon custom app goals and
particular system constraints, developers can run from ng2 to React, and back.
Opting for Angular, it usually assumes the creation of core skeleton for a front-end app,
whereas React.js can be applied to improve its specific parts. Moreover, it can be integrated
with other frameworks, like Backbone or even well-known Angular.
The scope is the binding part between the HTML (view) and the JavaScript
(controller).
The scope is an object with the available properties and methods.
The scope is available for both the view and the controller.
When you make a controller in AngularJS, you pass the $scope object as an
argument
When adding properties to the $scope object in the controller, the view (HTML) gets
access to these properties.
$Scope
The scope is a JavaScript object with properties and methods, which are available for
both the view and the controller.
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>
<scriptdr>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
</script>
Root Scope
All applications have a $rootScope which is the scope created on the HTML element that
contains the ng-app directive.
If a variable has the same name in both the current scope and in the rootScope, the
application use the one in the current scope.
<body ng-app="myApp">
<div ng-controller="myCtrl">
<p>The scope of the controller's favorite color:</p>
<h1>{{color}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.color = 'blue';
});
app.controller('myCtrl', function($scope) {
$scope.color = "red";
});
</script>
</body>
Output:
Example:-
Drawbacks of {{}}
Sometimes when we load our application in the browser , we can notice flashing content for
some milliseconds before {{ name }} is resolved and data is loaded.
This happens because the template is loaded before AngularJS had a chance to go in and
compile the elements. To resolve this issue, you can use ng-cloak directive.
Example:-
We are using the same expression which we used for double curly brackets.
In the first approach(i.e. {{}}), AngularJS evaluates the expression then replaces it with some
value which sometime be left with the flashing double curly brackets but ng-bind saves this
time by informing AngularJS to put the contents of the expression within the element itself.
Note:-
$scope is an object that is accessible from current component e.g Controller, Service only.
$rootScope refers to an object which is accessible from everywhere of the application we
can say it is a global scope of variable.
we can think $rootScope as global variable and $scope as local variables.
$rootScope is a parent object of all whereas $scope angular objects created in a web page.
app.controlller("ctrl",ctrl);
ctrl.$inject=["$scope"];
function ctrl($scope){
$scope.data="angularJS";
}
app.controlller("ctrl",ctrl);
ctrl.$inject=["$rootscope","$scope"];
function ctrl($rootscope,$scope){
$scope.data="angularJS";
$rootscope.my_un=function(){
return $scope.data;
}
}
}
35.About ngRoute :
app.js:
var app=angular.module("app",[ngRoute]);
page_one.html:
{{var_one}}
page_two.html:
{{var_two}}
page_one.js:
page_two.js
Step5,
config.js
app.config(config);
config.$inject=["$routeProvider"];
function config($routeProvider){
$routeProvider.when("/page_one",{
templateUrl:'templates/page_one.html'
controller: /'page_one'})
.when("/page_two",{
templateUrl:'templates/page_two.html'
controller: /'page_two''})
.otherwise("/page_one",{
templateUrl:'templates/page_one.html'
controller: /'page_one'});
}
index.html
<a href="#/page_one">page_one</a><br/>
<a href="#/page_two">page_two</a><br/>
<div ng-view>
</div>
ngRoute Ui.router
4)won’t support object passing as url 4)will support object passing as url
parameters parameters
5)syntax:
5)syntax:
$stateprovider.state("page_one",{
url:"/page_one", $routeProvider.when("/page_one",{
templateUrl: 'templates'/page_one.html', templateUrl:'templates/page_one.html'
controller:'page_one}') controller: /'page_one'})
6) parameters: 6) parameters:
$stateparams $routeparams
7) 7) ui-router allows for us to have strong-
Uses href for linking type linking between states based on state
names. Change the url in one place will
update every link to that state when you
build your links with ui-sref
8) keys in source page should start with “#” 8) not required
37.What is Routing?
Loading the Target Templates to the Source Templates without refreshing is called as
Routing in Single Page Application
If you want to navigate to different pages in your application, but you also want the
application to be a SPA (Single Page Application), with no page reloading, you can use
the ngRoute module.
ngRoute Module: The ngRoute Module routes your application to different pages
without reloading the entire application.
The UI-Router is a routing framework for AngularJS built by the AngularUI team. It provides
a different approach than ngRoute in that it changes your application views based on state
of the application and not just the route URL.
When using ngRoute, you’d have to use ngInclude or other methods and this could get
confusing. Now that all of your states, routing, and views are handled in your one .config(),
this would help when using a top-down view of your application.
bower.json –
dependencies:{
"angular":"~1.6.0",
"angular-ui-router":"~0.2.18"
.bowerrc.json -
"directory":"bower_components"
app.js -
var app=angular.module("app",["ui.router"]);
Step 3 :
-----------------------
Basic_uiRouter
templates
page_one.html
page_two.html
-------------------------
page_one.html-
{{var_one}}
page_two.html-
{{var_two}}
-----------------------------
Basic_uiRouter
controllers
page_one.js
page_two.js
-----------------------------
page_one.js-
page_two.js-
config.js -
app.config(config);
config.$inject=["$stateProvider","$urlRouterProvider"];
function config($stateProvider,$urlRouterProvider){
$stateProvider.state("page_one",{
url:"/page_one",
templateUrl:'templates/page_one.html',
controller:'page_one'
})
.state("page_two",{
url:"/page_two",
templateUrl:'templates/page_two.html',
controller:'page_two'
});
$urlRouterProvider.otherwise("/page_one");
index.html-
<html ng-app="app">
<a ui-sref="page_one"><b>Page_One</b></a>
<a ui-sref="page_two"><b>Page_Two</b></a>
<div ui-view>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-
router.min.js"></script>
<script src="app.js"></script>
<script src="config.js"></script>
<script src="controllers/page_one.js"></script>
<script src="controllers/page_two.js"></script>
</html>
Services:
It provides us method to keep data across the lifetime of the angular app
It provides us method to communicate data across the controllers in a consistent
way
This is a singleton object and it gets instantiated only once per application
It is used to organize and share data and functions across the application
Service() method:
Example:
app.service(“my_service”,my_service);
function my_service(){
this.my_fun=function(){
Var myClass=function(data) {
return data;
}
Factory() method:
Example:
app.factory(“my_service”,my_service);
function my_service(){
Provider() method:
Provider functions are constructor functions, whose instances are responsible for
"providing" a factory for a service.
Example:
app.provider(“my_service”,my_service);
function my_service(){
this.$get=function(){
Value() method:
Example:
app.value(“my_service”,”first_value”);
app.value(“myservice”,”second value”);
output:
second value.
Constant() method:
App.constant(“my_service”,”first_value”);
app.constant(“myservice”,”second value”);
output:
first value.
Gives us the instance of a function (object)- You just instantiated with the ‘new’
keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you
pass the service into your controller, those properties on ‘this’ will now be available on
that controller through your service. (Hypothetical Scenario)
Singleton and will only be created once
Reusable components
Dependencies are injected as constructor arguments
Used for simple creation logic
If you're using a class you could use the service provider
Syntax: module.service(‘serviceName’, function);
We will see simple example of using one way data binding in angularjs.
We can achieve this two-way data binding using ng-model directive. If we use ng-model
directive in html control it will update value automatically whenever data got changed in
input control.
How does data binding work in the AngularJs?
In AngularJs, it will remember present values and compare it with previous value. If any
changes found in previous value that time change event will fire automatically and it will
update data every time when data got changed.
The HTML tells the AngularJs compiler to create the $watch for controller methods and its
run inside the $apply method. We will see simple example for two way data binding in
angularjs.
In AngularJS, services are reusable singleton objects that are used to organize and share
code across your app. They can be injected into controllers, filters,
directives. AngularJS provides you three ways :
Service
factory
provider to create a service.
AngularJS .factory
module.factory('MyService', function() {
factory.method1 = function() {
//..
}
factory.method2 = function() {
//..
}
return factory;
});
AngularJS .service
module.service('MyService', function() {
this.method1 = function() {
//..
}
this.method2 = function() {
//..
}
});
Example
Following example will showcase all the above mentioned directives.
testAngularJS.htm
<html>
<head>
<title>Angular JS Services</title>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp"
ng-controller="CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});
</body>
</html>
In AngularJS you can make your own service, or use one of the many built-in services.
What is a Service?
In AngularJS, a service is a function, or object, that is available for, and limited to, your
AngularJS application.
The $location service has methods which return information about the location of the
current web page:
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<h3>{{myUrl}}</h3>
</div>
<p>This example uses the built-in $location service to get the absolute url of the page.</p>
<script>
$scope.myUrl = $location.absUrl();
});
</script>
</body>
</html>
Output:
https://www.w3schools.com/angular/tryit.asp?filename=try_ng_services
This example uses the built-in $location service to get the absolute url of the page.
For many services, like the $location service, it seems like you could use objects that are
already in the DOM, like the window.location object, and you could, but it would have some
limitations, at least for your AngularJS application.
AngularJS constantly supervises your application, and for it to handle changes and events
properly, AngularJS prefers that you use the $location service instead of
the window.location object.
The $http service is one of the most common used services in AngularJS applications. The
service makes a request to the server, and lets your application handle the response.
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<h1>{{myWelcome}}</h1>
</div>
<p>The $http service requests a page on the server, and the response is set as the value of
the "myWelcome" variable.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script>
</body>
</html>
OUTPUT:
The $http service requests a page on the server, and the response is set as the value of the
"myWelcome" variable.
Example
Display a new message after two seconds:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<h1>{{myHeader}}</h1>
</div>
<script>
$timeout(function () {
}, 2000);
});
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<h1>{{theTime}}</h1>
</div>
<script>
$interval(function () {
}, 1000);
});
</script>
</body>
</html>
9:19:05 PM
$scope is used for communicate between controller and view. $scope binds a view (DOM
element) to the viewmodel
But rootscope, There is only one rootscope in the app and it is shared among all the
components of an app. $rootscope a global variable. all others $scopes are children of
that $rootScope.
For Example
there are two controllers both have scope
Creating our own directives based on the apllication requirement called as custom
directive..
To create the custom directive we have to know the properties of the custom directives
templateUrl: Used to add the external templates(html files) to the custom directives.
Controller: Used to declare the controllers for the templates of custom directives.
Element level :
app.directive(“my_directive”,my_directive);
function my_directive(){
return{
restrict: ‘E’, // we have A and C also the values of the property restrict
In index.html
Attribute level :
app.directive(“attrType”, attrType);
return{
templateUrl: ‘ templates/sample.html’ ,
controller:’sample’
} }
In index.html
Class level:
app.directive(“classType”, classType);
return{
controller:’sample’
In index.html
app.directive(“allType”,allType);
function allType(){
return {
restrict: ’CAE’,
templateUrl: ‘ templates/sample.html’ ,
controller:’sample’
In index.html
<all_type></all_type>
$http:
This is predefined service that facilitates the communication with the remote HTTP
servers. $ http makes a request to the server and returns a response.
Example:
app.service(“my_service”,my_service);
my_service.$inject = [“$http”];
function my_service($hhtp){
this.fun_one = function(){
return
$http.get(“https://www.w3schools.com/angular/customers.php”).then(function(response){
return response.data;
})
$q:
this predefine service is used to make asynchronous calls to the server and also used to
reduce the duplicate code
for example when there are number calls hitting the server using $hhtp service and all the
calls will done using $q
this.fun_one = function(){
return
$http.get(“https://www.w3schools.com/angular/customers.php”).then(function(response){
deffered1.resolve(response.data);
return deffered.promise;
},function(response){
deffered1.reject(response.data);
return deffered1.promise;
})
}
Note: promise is used to close the asynchronous call whether the response is positive or
negative..
In ctrl.js file
app.controller("ctrl",ctrl);
ctrl.$inject=["$scope","my_service","$q"];
function ctrl($scope,my_service,$q) {
$q.all([my_service.fun_one(),my_service.fun_two(),my_service.fun_three()]).then(functio
n (response) {
$scope.var_one=response[0];
$scope.var_two=response[1];
$scope.var_three=response[2];
});
Directives are used to enhance the html capabilities and There are two types of directives
1. Predefined directives
2. Custom directives
Predefined directives: The directives given by the framework are called pre defined
directives..
Custom directives: creating our own directives based on the application requirement are
called as custom directives
1.element
2. attribute
3.css class
The HEAD method is identical to GET except that the server MUST NOT return a message-
body in the response. The metainformation contained in the HTTP headers in response to a
HEAD request SHOULD be identical to the information sent in response to a GET request.
This method can be used for obtaining metainformation about the entity implied by the
request without transferring the entity-body itself. This method is often used for testing
hypertext links for validity, accessibility, and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the information
contained in the response MAY be used to update a previously cached entity from that
resource. If the new field values indicate that the cached entity differs from the current
entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-
Modified), then the cache MUST treat the cache entry as stale.
The HEAD method is functionally similar to GET, except that the server replies with a
response line and headers, but no entity-body. The following example makes use of HEAD
method to fetch header information about hello.htm:
The server response against the above GET request will be as follows:
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
ETag: "34aa387-d-1568eb00"
Vary: Authorization,Accept
Accept-Ranges: bytes
Content-Length: 88
Content-Type: text/html
Connection: Closed
You can notice that here server the does not send any data after header.
// Create 5 promises
var promises = [];
var names = [];
for (var i = 1; i <= 5; i++) {
var willSucceed = true;
if (i == 2) willSucceed = false;
promises.push(createPromise('Promise' + i, i, willSucceed));
}
Output:
$q test
Promise1: Completed
Promise2: Failed
Promise3: Completed
Promise4: Completed
Promise5: Completed
Status1: Failed
Status2: Done waiting
53.what are the types of scopes available in custom directives
Scope is an object that refers to the application model. It is an execution context
for expressions. Scopes are arranged in hierarchical structure which mimic the DOM
structure of the application. Scopes can watch expressions and propagate events.
This is to ease the understanding of the $scope in the custom directives. While creating
custom directives we have to apply different types of functionalities, so for that we must
know about the $scope behavior in the directives.
$scope has a very important role in AngularJS, it works as a mediator (or like a glue)
between the logic & view in an Angular application. Now if we talk about the custom
directives, then first question which arises is-
“In any application if we want some specific functionality and we want to reuse that in
whole application module, then for this we need to develop a set of code. Angular calls it
directives.”
I am not going to discuss so much about custom directives basics here. In this blog I am just
focusing on use of $scope into directives.
So, when we create a custom directive it has a default scope, which is the parent scope (the
controller’s scope from where the directive is called). This behavior is by default, until and
unless we do not set the scope.
In this blog I will talk about the scope properties, they are false, true, {}.
In layman language false is assumed as no, so if the scope is set to false, then it means use
parent scope in the directive and do not create a new scope for the directive itself. It just
uses the scope of respective controller. So let us suppose if we have a controller named
“homeController” and a directive “printName”, then in printName directive we will get
parent scope by default and any change in scope values, either child or parent, will reflect
in both.
Example:
Code Snippet
$scope.name = “rock”;
});
app.directive(“sharedDirective”, function () {
return {
restrict: “EA”,
scope: false,
};
});
//view (html)
<div ng-app=”blogDemo”>
</div>
</div>
In this example, we can see whenever the value of parent scope changes, it will reflect
in the directive scope also, because they both are sharing the same scope object.
Using this property, the directive will create a new scope for itself. And inherit it from
parent scope. If we do any changes to the controller scope it will reflect on directive scope,
but it won’t work the other way around. This is because both of them use their own copies
of scope object.
Example:
Code Snippet
var app = angular.module(“blogDemo”,[]);
app.controller(“inheritedController”,function($scope){
});
app.directive(“inheritedDirective”, function(){
return {
restrict: “EA”,
scope: true,
};
});
//view (html)
<div ng-app=”blogDemo”>
</div>
</div>
In this example when the first time directive loads, the screen will show the value of parent
scope. But when we will change the value from text box. Then this will only change into
child scope only. Means no change in parent scope.
One of the important features, its called isolated scope. Here too the directive will create a
new scope object but it is not inherited by the parent scope, so now this scope doesn’t
know anything about the parent scope.
But the question arises, if we do not have the link from parent scope then how can we get
the values from it, and how can we modify it ?
The answer is- set the objects property into DDO, but for this it is necessary to set on
attributes into the directive.
In isolated scope we use three prefixes which helps to bind the property or methods from
the controller (parent scope) to directive (isolated scope). Lets understand how this works.
Whenever a directive finds any prefixes in its scope property in DDO, it checks it in directive
declaration (in html page where the directive is called) with attribute declared on this
element. We can also change the name by giving a separate attribute name after any of the
prefixes.
One way binding means a parent sending anything to the directive scope through the
attribute, gets reflected in the directive. But if any change in the directive happens it will not
reflect in parent. The @ is used to pass string values.
Example:
Code Snippet
//module
//controller
app.controller(‘OneWayController’, [‘$scope’, function ($scope) {
$scope.student = {
name: ‘Rohit’,
class: ‘MCA’,
Address: ‘New Delhi’
};
}]);
// directive
app.directive(‘oneWayDirective’, function () {
return {
scope: {
name: ‘@’
},
};
});
//view (html)
<one-way-directive name=”{{ student.name }}”></one-way-directive>
or
<one-way-directive studName=”{{ student.name }}”></one-way-directive>
then directive would be with a change in scope property.
Code Snippet
app.directive(‘oneWayDirective’, function () {
return {
scope: {
name: ‘@studName’
},
};
});
This is called two way binding, because the parent scope will also reflect to directive scope
vice-versa.
It is used for passing object to the directive instead of string. This object could be changed
from both sides, from parent or from directive. That is why it is called two-way.
Example:
Code Snippet
//module
var blogDemo = angular.module(‘myApp’,[]);
//directive
blogDemo.directive(‘twoWayDirective’, function() {
return {
restrict: ‘EA’,
scope: { obj: “=”},
};
});
//controller
blogDemo.controller(‘blogController’, function ($scope) {
});
//view (html)
<div ng-controller=”blogController”>
</div>
Used to bind any parent’s method to directive scope. Whenever we want to call the parent
methods from the directive we can use this. It is used to call external (outside of current
scope) functions. Overall “&” is used to pass data as a function or method.
Example:
Code Snippet
//module
var blogDemo = angular.module(‘myApp’,[]);
//directive
blogDemo.directive(‘methodDirective’, function() {
return {
scope: {
studData: ‘=’,
swap: ‘&’
},
};
});
//controller
blogDemo.controller(‘blogController’, function ($scope) {
$scope.swapData = function () {
$scope.customer = {
fname: ‘Raj’,
lname: ‘kumar’
};
};
});
//view (html)
<div ng-controller=”blogController”>
</div>
In this example the directive creates a property inside its local scope, that is swapData. We
can also understand swap as an alias for swapData. So we pass a method to ‘&’ which is
then invoked by the directive whenever required.
Summarizing, Shared scope (sharing the same scope and data, can not pass the data
explicitly), Inherited scope (parent scope values can be fetched into child but child means
directive scope will not effect parent), Isolated scope (both controller & directive do not
share the scope & data, we can explicitly pass the data using some parameters that is @,
& ,= ).
The name of the Component (as string).The Component config object. (Note that, unlike
the .directive() method, this method does not take a factory function.)
Index.js
(function(angular) {
'use strict';
this.hero = {
name: 'Spawn'
};
});
})(window.angular);
heroDetail.js
(function(angular) {
'use strict';
function HeroDetailController() {
angular.module('heroApp').component('heroDetail', {
templateUrl: 'heroDetail.html',
controller: HeroDetailController,
bindings: {
hero: '='
});
})(window.angular);
Index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-heroComponentSimple-production</title>
<script src=
” https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="index.js"></script>
<script src="heroDetail.js"></script>
</head>
<body ng-app="heroApp">
<b>Hero</b><br>
<hero-detail hero="ctrl.hero"></hero-detail>
</div>
</body>
</html>
heroDetail.html
<span>Name: {{$ctrl.hero.name}}</span>
compilation phase a directive also has a chance to modify the DOM node
before a scope is attached to it;
compilation phase we do not have access to the $scope data
if the directive needs to access the scope, its link function allows that
In the link phase the data i.e. ($scope) is attached to the template function and executed to
get the final HTML output.
The concept of compile and link comes from C language, where you first compile the code and
then link it to actually execute it. The process is very much similar in AngularJS as well.
The Process
1. Compile – $compile function traverse the DOM and collect all directives from DOM. For each
directive it finds, it adds it to a list of directives. Once the entire DOM has been traversed, it will
sort that list of directives by their priority. It takes our HTML markup or template one by one and
returns a link function.
1var $compile = ...; // injecte $comple into our code to get link function
2var scope = ...; // scope for new directive
3var parent = ...; // DOM element where we want to apply our directive
4var html = '<div ng-show="data"></div>'; // Our HTML code
5
6var template = angular.element(html); // Step 1A: parse HTML into DOM element to pass
7in $compile to get link function
8
var linkFn = $compile(template); // Step 1B: compile the template and return link
function
2. Link – The above link function (Returned by $compile function) combines the directives with a
scope to give as two way data binding. Any data-related changes affecting the model are
immediately propagated to the matching view(s), and any changes made in the view(s) are
reflected in the underlying model.
1var element = linkFn(scope); // Step 2A: link 'scope' with the compiled template (Two way
2binding).
3
parent.appendChild(element); // Step 2B: Inject our element to parent DOM element
This can help in scenarios where you get some Markup as a string, and want it to use it
with AngularJS, you’ll need to compile the HTML to make it work.
Hope this will help you to understand the compilation process in angular.js.
Requirements is to add html content dynamically and that content might have a click event
on it.
So the code Angular code I have below displays a button, and when clicked, it dynamically
adds another button. Clicking on the dynamically added buttons, should add another
button, but I cannot get the ng-click to work on the dynamically added buttons
Index.html
<!DOCTYPE html>
<html lang="en" >
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js">
</script>
<script src="app.js"></script>
<link rel="stylesheet" href="my_style.css">
<script src="controllers/ctrl.js"></script>
<div ng-app="app" ng-controller="Ctrl">
<button class="addfields" ng-click="addNewChoice()">Add choice</button>
<fieldset data-ng-repeat="choice in choicesA">
<input type="text" ng-model="choice.name" name="" placeholder="Enter name">
<button class="remove" ng-click="removeChoice($index)">-</button>
<button class="addfields" ng-click="addNewChoiceB(choice)">Add fields</button>
<div data-ng-repeat="choiceb in choice.choicesB">
<input type="text" ng-model="choiceb.name" name="" placeholder="Enter field">
<button class="remove" ng-click="removeChoiceB(choice,$index)">-</button>
</div>
</fieldset>
<div id="choicesDisplay">
<pre>choicesA = {{ choicesA }}</pre>
<pre data-ng-repeat="choiceb in choicesA">choicesB = {{ choiceb.choicesB }}</pre>
</div>
</div>
</html>
app.js
my_style.css
fieldset {
background: #FCFCFC;
padding: 16px;
border: 1px solid #D5D5D5;
}
.addfields {
margin: 10px 0;
}
#choicesDisplay {
padding: 10px;
background: rgb(227, 250, 227);
border: 1px solid rgb(171, 239, 171);
color: rgb(9, 56, 9);
}
.remove {
background: #C76868;
color: #FFF;
font-weight: bold;
font-size: 21px;
border: 0;
cursor: pointer;
display: inline-block;
padding: 4px 9px;
vertical-align: top;
line-height: 100%;
}
input[type="text"],
select {
padding: 5px;
}
Ctrl.js
app.controller('Ctrl',Ctrl);
Ctrl.$inject("$scope")
function Ctrl($scope) {
$scope.choicesA = [{
id: 'choice1',
choicesB:[]
}, {
id: 'choice2',
choicesB:[]
}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choicesA.length + 1;
$scope.choicesA.push({
'id': 'choice' + newItemNo,
choicesB:[]
});
};
$scope.removeChoice = function(ind) {
$scope.choicesA.splice(ind,1);
};
$scope.addNewChoiceB = function(choice) {
var newItemNo = choice.choicesB.length + 1;
choice.choicesB.push({
'id': 'choice' + newItemNo
});
};
$scope.removeChoiceB = function(choice,ind) {
choice.choicesB.splice(ind,1);
};
};
62. 53 62 same questions
63. 63- 54 same questions.
AngularJS is a great JavaScript framework that has some very compelling features for not
only developers, but designers as well! In this tutorial, we will cover what I consider to be
the most essential features, and how they can help make your next web application
awesome.
To get an idea of what you can do with AngularJS, check out the range of AngularJS items on
Envato Market. You can find an image cropper, an eCommerce web application, a JSON
editor, and much more.
In this article, we will cover a few of the most important AngularJS concepts to get the "big
picture." It is my goal that, after seeing some of these features, you will be excited enough
to go and build something fun with AngularJS.
Think of your model as the single-source-of-truth for your application. Your model is where
you go to to read or update anything in your application.
Data-binding is probably the coolest and most useful feature in AngularJS. It will save you
from writing a considerable amount of boilerplate code. A typical web application may
contain up to 80% of its code base, dedicated to traversing, manipulating, and listening to
the DOM. Data-binding makes this code disappear, so you can focus on your application.
Think of your model as the single-source-of-truth for your application. Your model is where
you go to to read or update anything in your application. The data-binding directives
provide a projection of your model to the application view. This projection is seamless, and
occurs without any effort from you.
Traditionally, when the model changes, the developer is responsible for manually
manipulating the DOM elements and attributes to reflect these changes. This is a two-way
street. In one direction, the model changes drive change in DOM elements. In the other,
DOM element changes necessitate changes in the model. This is further complicated by user
interaction, since the developer is then responsible for interpreting the interactions,
merging them into a model, and updating the view. This is a very manual and cumbersome
process, which becomes difficult to control, as an application grows in size and complexity.
There must be a better way! AngularJS' two-way data-binding handles the synchronization
between the DOM and the model, and vice versa.
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-1.0.0rc10.min.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<hr>
<h1>Hello, {{yourName}}!</h1>
</div>
</body>
</html>
Feature 2: Templates
It's important to realize that at no point does AngularJS manipulate the template as strings.
It's all the browser DOM.
It is important to realize that at no point does AngularJS manipulate the template as strings.
The input to AngularJS is browser DOM and not an HTML string. The data-bindings are DOM
transformations, not string concatenations or innerHTML changes. Using the DOM as the
input, rather than strings, is the biggest differentiation AngularJS has from its sibling
frameworks. Using the DOM is what allows you to extend the directive vocabulary and build
your own directives, or even abstract them into reusable components!
One of the greatest advantages to this approach is that it creates a tight workflow between
designers and developers. Designers can mark up their HTML as they normally would, and
then developers take the baton and hook in functionality, via bindings with very little effort.
function AlbumCtrl($scope) {
scope.images = [
{"thumbnail":"img/image_01.png", "description":"Image 01
description"},
{"thumbnail":"img/image_02.png", "description":"Image 02
description"},
{"thumbnail":"img/image_03.png", "description":"Image 03
description"},
{"thumbnail":"img/image_04.png", "description":"Image 04
description"},
{"thumbnail":"img/image_05.png", "description":"Image 05 description"}
];
}
<div ng-controller="AlbumCtrl">
<ul>
</li>
</ul>
</div>
It is also worth mentioning, as a side note, that AngularJS does not force you to learn a new
syntax or extract your templates from your application.
Feature 3: MVC
AngularJS incorporates the basic principles behind the original MVC software design pattern
into how it builds client-side web applications.
The Model
The model is simply the data in the application. The model is just plain old JavaScript objects.
There is no need to inherit from framework classes, wrap it in proxy objects, or use special
getter/setter methods to access it. The fact that we are dealing with vanilla JavaScript is a
really nice feature, which cuts down on the application boilerplate.
The ViewModel
A viewmodel is an object that provides specific data and methods to maintain specific views.
The Controller
The View
The view is the HTML that exists after AngularJS has parsed and compiled the HTML to
include rendered markup and bindings.
AngularJS has a built-in dependency injection subsystem that helps the developer by making
the application easier to develop, understand, and test.
Dependency Injection (DI) allows you to ask for your dependencies, rather than having to go
look for them or make them yourself. Think of it as a way of saying "Hey I need X', and the
DI is responsible for creating and providing it for you.
To gain access to core AngularJS services, it is simply a matter of adding that service as a
parameter; AngularJS will detect that you need that service and provide an instance for you.
You are also able to define your own custom services and make those available for injection
as well.
angular.
module('MyServiceModule', []).
win.alert(msg);
};
}]);
notifyService(msg);
};
Feature 5: Directives
Directives are my personal favorite feature of AngularJS. Have you ever wished that your
browser would do new tricks for you? Well, now it can! This is one of my favorite parts of
AngularJS. It is also probably the most challenging aspect of AngularJS.
Directives can be used to create custom HTML tags that serve as new, custom widgets. They
can also be used to "decorate" elements with behavior and manipulate DOM attributes in
interesting ways.
Here is a simple example of a directive that listens for an event and updates its $scope,
accordingly.
myModule.directive('myComponent', function(mySharedService) {
return {
restrict: 'E',
$scope.$on('handleBroadcast', function() {
});
},
replace: true,
template: '<input>'
};
});
1 <my-component ng-model="message"></my-component>
The AngularJS team feels very strongly that any code written in JavaScript needs to come
with a strong set of tests. They have designed AngularJS with testability in mind, so that it
makes testing your AngularJS applications as easy as possible. So there's no excuse for not
doing it.
Given the fact that JavaScript is dynamic and interpreted, rather than compiled, it is
extremely important for developers to adopt a disciplined mindset for writing tests.
AngularJS is written entirely from the ground up to be testable. It even comes with an end-
to-end and unit test runner setup. If you would like to see this in action, go check out the
angular-seed project at https://github.com/angular/angular-seed.
Once you have the seed project, it's a cinch to run the tests against it. Here is what the
output looks like:
The API documentation is full of end-to-end tests that do an incredible job of illustrating
how a certain part of the framework should work. After a while, I found myself going
straight to the tests to see how something worked, and then maybe reading the rest of the
documentation to figure something out.
That is one approach to support Dependency Injection after your code is minified (if you
choose to minify).
function ($scope,notify)
When you minify the code, your function will look like this:
function (a,b)
Since AngularJS uses the function parameter names to infer DI, your code will break
because AngularJS doesn't know about a or b.
To solve this problem, they provided additional ways to declare controllers (or other
services/factories/etc) for that matter:
1) For controllers, use the $inject method - here you pass an array of literals that map to
the parameters of your controller function. So, if you provide
[“$scope”,”notify”]
then the value of the first parameter to your function will be the a scope object
associated with this controller and the second parameter will be the notify service.
2) When declaring new controllers, services, etc, you can use the array literal syntax.
Here, you do something like this:
angular.module(“myModule”).controller(“MyController”,
[“$scope”,”notify”,function($scope,notify{
……...
}]);
The array as a parameter to the controller function maps the DI objects to your function
parameters
AngularJS handle data-binding mechanism with the help of three powerful functions:
$watch(), $digest() and $apply(). Most of the time AngularJS will call the $scope.$watch()
and $scope.$digest() functions for you, but in some cases you may have to call these
functions yourself to update new values.
$digest() - This 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 checks if
the value of the expression has changed. If the value has changed, AngularJS calls the
listener with the new value and the old value. The $digest() function is called whenever
AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call.
You may have some cases where AngularJS does not call the $digest() function for you.
In that case you have to call it yourself.
$apply() - Angular do auto-magically updates only those model changes which are inside
AngularJS context. When you do change in any model outside of the Angular context
(like browser DOM events, setTimeout, XHR or third party libraries), then you need to
inform Angular of the changes by calling $apply() manually. When the $apply() function
call finishes AngularJS calls $digest() internally, so all data bindings are updated.
mod.service("myService", function() {
var name = "Bob";
this.setName = function(newName) {
You are returning an object with this.name = newName;
service
methods. };
this.getName = function() {
return this.name;
}});
this.$get = function() {
return new function() {
this.sayHi = function() {
console.log("Hi " + name;
};
};
};});
mod.config(function(greeterProvider) {
greeterProvider.setName(“John");
});
To drive the point home one last time here is a image of a provider with the factory,
value, and service portions highlighted:
68..dff bwn emit and broadcast
AngularJS provides $on, $emit, and $broadcast services for event-based communication
between controllers.
$emit
It dispatches an event name upwards through the scope hierarchy and notify to the
registered $rootScope.Scope listeners. The event life cycle starts at the scope on which
$emit was called. The event traverses upwards toward the root scope and calls all
registered listeners along the way. The event will stop propagating if one of the listeners
cancels it.
<!DOCTYPE html>
<html>
<head>
<title>Broadcasting</title>
<script src="lib/angular.js"></script>
<script>
var app = angular.module('app', []);
聽
app.controller("firstCtrl", function ($scope) {
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
console.log($scope.message);
});
});
聽
app.controller("secondCtrl", function ($scope) {
$scope.handleClick = function (msg) {
$scope.$emit('eventName', { message: msg });
};
});
聽
</script>
</head>
<body ng-app="app">
<div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;">
<h1>Parent Controller</h1>
<p>Emit Message : </p>
<br />
<div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;">
<h1>Child Controller</h1>
<input ng-model="msg">
<button ng-click="handleClick(msg);">Emit</button>
</div>
</div>
</body>
</html>
How it works..
$broadcast
It dispatches an event name downwards to all child scopes (and their children) and notify
to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on
which $broadcast was called. All listeners for the event on this scope get notified.
Afterwards, the event traverses downwards toward the child scopes and calls all
registered listeners along the way. The event cannot be canceled.
<!DOCTYPE html>
<html>
<head>
<title>Broadcasting</title>
<script src="lib/angular.js"></script>
<script>
var app = angular.module('app', []);
聽
app.controller("firstCtrl", function ($scope) {
$scope.handleClick = function (msg) {
$scope.$broadcast('eventName', { message: msg });
};
});
聽
app.controller("secondCtrl", function ($scope) {
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
console.log($scope.message);
});
});
聽
</script>
</head>
<body ng-app="app">
<div ng-controller="firstCtrl" style="border:2px solid #E75D5C; padding:5px;">
<h1>Parent Controller</h1>
<input ng-model="msg">
<button ng-click="handleClick(msg);">Broadcast</button>
<br /><br />
<div ng-controller="secondCtrl" style="border:2px solid #428bca;padding:5px;">
<h1>Child Controller</h1>
<p>Broadcast Message : </p>
</div>
</div>
</body>
</html>
How it works..
$on
It listen on events of a given type. It can catch the event dispatched by $broadcast and
$emit.
Note
1.
If there is no parent-child relation between your scopes you can inject $rootScope into
the controller and broadcast the event to all child scopes but you cannot emit your
event.
2.
3.
You can emit your event only when you have parent-child relation and event
propagation is initiated by child. However, $emit can fire an event only for all
$rootScope.$on listeners.
AngularJS directives allow us to use our own vocabulary to create semantic HTML
components. To take advantage of that we should be aware of how it works to avoid
some annoying and hard to find issues.
Defining (the JS)
To define a new custom directives all we need to do is use the directive method which
expects two parameters: a name and a constructor function.
angular.module('myDirectives', []).
directive('myAwesomeDirective', function() {
return {
restrict: 'E',
template: '<h1>This is awesome!</h1>'
};
});
In this case, the name must be written using camelCase and each capital letter will
represent a dash when we use this directive.
Using (the HTML)
<my-awesome-directive></my-awesome-directive>
In this case, the name must be written using dashes and each dash represents a capital
letter from the directive definition.
Use an unique preffix
I see a lot of times people starting with Angular, which by instinct name their directives
with one word like: <dialog> or <tabs>. The reason why this is not a good ideia is because
we can have new HTML elements in the future (HTML6?) named exactly with the same
name of our custom directive. BTW this is the case of the <dialog> element.
To avoid naming collision with future HTML elements, use a preffix as a kind of
namespace
A recommended and wide spread convention from the Angular community is to have two
letters preffix names that identifies your application or library.
Examples:
Conclusion
TLDR;
Use camelCase in the JS and dash-separated in the HTML as expected by the AngularJS
compiler. Choose an unique two letters preffix for your directives and avoid the "ng-"
preffix.
71. how we can communicate angular with nodejs or any server side tech??
I’m assuming you have already set your enviroment, so we are going to start by creating
our NodeJS project, to do that I’m going to use express, if you don’t have it yet just install
via npm with the following command line:
express myNodeProject
When you do it you’ll see that express has already created the basic project structure for
you:
Folder Structure
By default, express uses Jade as the view engine, as you can see in the views folder we
already have some jade files, which we are not going use, you can get rid of them later if
you want. We’ll need to make some changes here to be able to use angularjs. Let’s begin
by opening the file routes/index.js, it contains the following code:
At this point you are already using angular and node in your application, but they are
kind of independent from each other, there are no communication between them. To
finish up this tutorial I’m going to show how AngularJS can make a request to NodeJS.
But before we do that, we need to come back to the index.js file (the one we just
modified) and create a function to return some data, which will be called when we make
the request from our angularjs controller, just copy the following code and paste it right
above the module.exports on your index.js.
router.get('/data', function(req,res){
res.json([{"id": 1, "name": "Mymm", "city": "Pantano do Sul"},
{"id": 2, "name": "Skyble", "city": "Guilmaro"},
{"id": 3, "name": "Tagfeed", "city": "Gnosjö"},
{"id": 4, "name": "Realcube", "city": "Jrashen"},
{"id": 5, "name": "Bluejam", "city": "Zhangjiawo"},
{"id": 6, "name": "Jayo", "city": "Obonoma"},
{"id": 7, "name": "Cogidoo", "city": "Sungsang"},
{"id": 8, "name": "Avavee", "city": "Diawara"},
{"id": 9, "name": "Tagtune", "city": "Monywa"},
{"id": 10, "name": "Centimia", "city": "Retkovci"}]);});
What is happening here is that the router.get function is assigning a function to the
url ‘/data’, so when the user types ‘/data’ in the browser, node will call this function,
which is doing nothing more than returning a json, it could be getting and handling data
from the database, but as I want to keep it simple, a static json will do the job.
Now let’s create our app.js file, as you can see in the HTML code, it’s already referenced
there. I’m going to put it on the public/javascript folder.
Now we just need to modify a little bit our HTML to make it iterate over our data and
show it on the screen, just add this to the div with the ng-controller:
Let’s take a quick look at how forms look without using this module.
<form name="userForm">
<input
type="text"
name="username"
ng-model="user.username"
ng-minlength="3"
ng-maxlength="8"
required>
</form>
We are explicitly showing each error message only if that error exists. This can get
tedious when we have multiple errors that we want to show.
This is where ngMessages comes in. This module brings some sanity to validation
messages.
Let’s take the above example and see how that would look in ngMessages.
<form name="userForm">
type="text"
name="username"
ng-model="user.username"
ng-minlength="3"
ng-maxlength="8"
required>
<div ng-messages="userForm.name.$error">
Much simpler! ngMessages will handle showing and hiding specific messages based on
the errors. ngMessages is basically looping through the userForm.name.$errors object
and displaying messages based on that.
#Using ngMessages
The setup for ngMessages is very simple. We just need to load the module after Angular
and then inject it into our application.
SHOW MESSAGES
Just use the ng-messages directive and pass in the field you want and its $error object.
<div ng-messages="<formName>.<inputName>.$error">
#A Sample App
THE HTML
We’re going to be using some very simple HTML here. We just need a form after all.
Here’s our index.html file:
<!DOCTYPE html><html><head>
<meta charset="utf-8">
ngMessages Demo</title>
<!-- load bootstrap and add some custom css -->
<script src="//code.angularjs.org/1.4.0/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js"></script>
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control"
ng-model="main.name"
ng-minlength="5"
ng-maxlength="10"
required>
<div class="form-group">
<label>Email</label>
ng-model="main.email"
ng-minlength="5"
ng-maxlength="20"
required>
<!-- ngMessages goes here -->
<div class="form-group">
</body></html>
This will be the starting template for our app. We are using novalidate on our form so
that we disable the HTML5 validations. We have our own validations and they look much
better.
We’ve started our HTML. Now we just need to create the Angular application that we
already referenced in app.js, ng-app and ng-controller.
.controller('MainCtrl', MainCtrl);
MainCtrl() {}
We don’t need to have anything in our controller right now, but this is where you would
process your form.
NGMESSAGES FOR NAME
NGMESSAGES FOR EMAIL
For our email input, let’s take a different approach. If our form has multiple fields, then it
can be tedious to create multiple ng-messages blocks. ngMessages gives us the ability to
pull messages from an external file.
This means we can reuse the same messages for multiple fields!
#Reusable ngMessages with File
Let’s create a new file called messages.html. We can place all of our messages in this file
and just call it with ng-messages-include.
Here’s the messages.html file:
<div ng-messages-include="messages.html"></div></div>
Let’s say we wanted to only show error messages after a user has clicked out of the input
that they are typing into. It isn’t very intuitive to show errors even before a user has used
an input.
For example, we can only show errors for the name input using the following:
We also want to use the Bootstrap provided classes (.has-error) to highlight the field as
red if there is an error. We can use ngClass to add the error class if the field is $invalid.
#Conclusion
With this simple module, Angular form validation has gotten that much easier. Try it out
in your own applications and let us know how you like it. Do you prefer ngMessages, a
third-party software like angular-formly or doing validation from scratch?
Then the user will have to call the function passing values that will be assigned to the
respective variables:
angular.module('DemoApp', [])
.controller('DemoController', ['$scope', '$log', function($scope, $log) {
$scope.message = "Hello World";
$log.debug('logging hello');
}]);
Here the controller method receives two parameters. The first is the name of the
controller ('DemoController'), the second is an array. In the array the last element is the
anonymous function while all the elements before are the names of the objects Angular
needs to pass to the function in the order it needs to pass them. Inside the function
declaration we have the same names in the same order. Note however that outside the
function declaration those are strings holding the names while inside they are the real
variable name.
examples/angular/dependency_injection_full.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <meta name="viewport"
6. content="width=device-width, initial-scale=1, user-scalable=yes">
7. <script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></scri
pt>
8.
9. <script>
10. angular.module('DemoApp', [])
11. .controller('DemoController', ['$scope', '$log', function($scope, $log) {
12. $scope.message = "Hello World";
13. $log.debug('logging hello');
14. }]);
15.
16. </script>
17.
18. </head>
19. <body ng-app="DemoApp" ng-controller="DemoController">
20.
21. <h1>Main Title</h1>
22.
23. </body>
24. </html>
25.
Try!
- AngularJs provides $http service for making ajax requests to remote servers.
- AngularJS provides $https: control which works as a service to read data from
the server.
- Once the data is ready, $https: can be used to get the data from server in the
following manner -
function studentController($scope,$https:) {
$https:.get(url).success( function(response) {
$scope.students = response;
});
}
$https: service makes an ajax call and sets response to its property students.
------------------------------------------------------------------------------------------------------------
----------------------------------------------------------
Features Of AngularJS:
1) MVC Architecture:
EX.<script type="text/javascript">
angular.module('testApp',[]);
angular.module('testApp',
['dependentModule1','dependentModule2']);
</script>
EX.
<div ng-controller='testController'>
<script>function testController($scope){
</script>
4)DIRECTIVES:
i.e they decorate html elements with new behaviors and help
to manipulate html elements attributes in interesting way.
5)TEMPLATES:
6)SERVICES:
7)ROUTING:
ngRoute:-
ui.router:-
Advantages Of AngularJS:
1) The Bootstrap Phase:- The first phase of the AngularJS life cycle is the
bootstrap phase,
and any dependencies are injected into your module and made
available to code within the module.
3) The Runtime Data Binding Phase:- The final phase of the AngularJS
application is the runtime phase,
any changes in the scope are reflected in the view, and any
changes in the view are directly updated in the scope,
making the scope the single source of data for the view.
DOM each time the data changes. AngularJS compiles the DOM
only once and then links the compiled template as necessary,
------------------------------------------------------------------------------------------------------------
---------------------------------------------------------
77. how do we hide html element by button click in AngularJS? With ng-hide
directive we can hide eliment by button click.
EX.
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
rel="stylesheet">
<script data-require="[email protected]"
src="https://code.angularjs.org/1.3.17/angular.js" data-
semver="1.3.17"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>
</html>
78. difference between one way data binding and two data dat binding.
Ex.
<!DOCTYPE html>
<html>
<head>
<title> AngularJs Two Binding Example </title>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></scrip
t>
<script type="text/javascript">
var app =
angular.module('angulartwobindapp', []);
app.controller('angulartwobindingCtrl',
function ($scope) {
});
</script>
</head>
<body ng-app="angulartwobindapp">
<div ng-controller="angulartwobindingCtrl">
</div>
</body>
</html>
Ex.
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></scrip
t>
<script type="text/javascript">
app.controller('angulartwobindingCtrl', function
($scope) {
});
</script>
</head>
<body ng-app="angulartwobindapp">
<div ng-controller="angulartwobindingCtrl">
</div>
</body>
</html>
79. Give the differences between AngularJS and Backbone and Knockout?
Comparison with Backbone.js and Knockout.js
~142 KB total
~ 7.3 KB total (gzip / ~21 KB total (gzip /
File Size (compressed and
minified) minified)
minified)
Version & V1.4.2 & MIT (Open- V1.2.1 & MIT (Open- V3.3.0 & MIT (Open-
Licence source) source) source)
Dependends on
Dependencies No Dependencies No Dependencies
underscore.js and jQuery
Does not support Can support jQuery's $.ajax It can support jQuery's
Data jQuery but we can and is very easy to $.ajax and knockout
use Angular's $http understand mapping
Design Can support the MVC It can support MVP design It can support the
and MVVM design
Pattern pattern MVVM design pattern
patterns
Conclusion
This article helps you to understand the AngularJs comparison with Backbone.js,
Knokout.js and its features.
$watch
This function is used to observe changes in a variable on the $scope. It accepts three
parameters: expression, listener and equality object, where listener and equality object
are optional parameters.
$watch(watchExpression, listener, [objectEquality])
Here, watchExpression is the expression in the scope to watch. This expression is called
on every $digest() and returns the value that is being watched.
The listener defines a function that is called when the value of the watchExpression
changes to a new value. If the watchExpression is not changed then listener will not be
called.
The objectEquality is a boolean type which is used for comparing the objects for equality
using angular.equals instead of comparing for reference equality.
<script>
scope.name = 'shailendra';
scope.counter = 0;
scope.$watch('name', function (newVal, oldVal) {
scope.counter = scope.counter + 1;
});
</script>
$watchgroup
This function is introduced in Angular1.3. This works the same as $watch() function
except that the first parameter is an array of expressions to watch.
$watchGroup(watchExpression, listener)
The listener is passed as an array with the new and old values for the watched variables.
The listener is called whenever any expression in the watchExpressions array changes.
<script>
$scope.teamScore = 0;
$scope.time = 0;
$scope.$watchGroup(['teamScore', 'time'], function(newVal, oldVal) {
if(newVal[0] > 20){
$scope.matchStatus = 'win';
}
else if (newVal[1] > 60){
$scope.matchStatus = 'times up';
});
</script>
$watchCollection
This function is used to watch the properties of an object and fires whenever any of the
properties change. It takes an object as the first parameter and watches the properties
of the object.
$watchCollection(obj, listener)
The listener is called whenever anything within the obj has been changed.
<script>
$scope.names = ['shailendra', 'deepak', 'mohit', 'kapil'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function (newVal, oldVal) {
$scope.dataCount = newVal.length;
});
</script>
I hope you will enjoy the watchers in AngularJS while developing your app with
AngularJS. I would like to have feedback from my blog readers. Your valuable feedback,
question, or comments about this article are always welcome
AngularJS has a powerful data binding mechanism. When you do changes in a variable
on the $scope object within your view, the $scope object auto-magically updates itself.
Similarly, whenever the $scope object changes, the view updates itself with the new
value. AngularJS handle data-binding mechanism with the help of three powerful
functions: $watch(), $digest() and $apply(). Most of the time AngularJS will call the
$scope.$watch() and $scope.$digest() functions for you, but in some cases you may have
to call these functions yourself to update new values. Therefore it is really good to know
how they work.
$watch()
$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 checks
if the value of the expression has changed. If the value has changed, AngularJS calls the
change callback(listener) with the new value and the old value.
The $digest() function is called whenever AngularJS thinks it is necessary. For example,
after a button click, or after an AJAX call. You may have some corner cases where
AngularJS does not call the $digest() function for you. In that case you may have to call
this function yourself.
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Digest</title>
<script src="lib/angular.js"></script>
<script>
var myapp = angular.module("myapp", []);
var myController = myapp.controller("myController", function ($scope) {
聽
$scope.datetime = new Date();
聽
$scope.updateTime = function () {
$scope.datetime = new Date();
}
聽
document.getElementById("updateTimeButton").addEventListener('click',
function () {
console.log("update time clicked");
$scope.datetime = new Date();
聽
console.log($scope.datetime);
});
});
</script>
聽
</head>
<body ng-app="myapp" ng-controller="myController">
<button ng-click="updateTime()">Update time - ng-click</button>
<button id="updateTimeButton">Update time</button>
<br />
</body>
</html>
When you will click on second button, the data binding is not updated. Since $scope.
$digest() is not called after the second button's event listener is executed. In this way on
clicking the second button the time will be updated in the $scope.data.time variable, but
the new time will never displayed.
To fix this issue you need to add a $scope.$digest() call to the second button event
listener, like this:
<script type="text/javascript">
document.getElementById("updateTimeButton").addEventListener('click',
function () {
console.log("update time clicked");
$scope.datetime = new Date();
聽
//to update $scope
$scope.$digest();
console.log($scope.datetime);
});</script>
$apply()
Angular do auto-magically updates only those model changes which are inside AngularJS
context. When you do change in any model outside of the Angular context (like browser
DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular
of the changes by calling $apply() manually. When the $apply() function call finishes
AngularJS calls $digest() internally, so all data bindings are updated.
In above example, instead of calling $digest() function inside the button listener function
you can used the $apply() function like this:
<script>
document.getElementById("updateTimeButton").addEventListener('click',
function () {
$scope.$apply(function () {
console.log("update time clicked");
$scope.datetime = new Date();
聽
console.log($scope.datetime);
});
});
</script>
Note
$digest() is faster than $apply(), since $apply() triggers watchers on the entire scope
chain while $digest() triggers watchers on the current scope and its children(if it has).
When error occurs in one of the watchers, $digest() can not handled errors via
$exceptionHandler service, In this case you have to handle exception yourself. While
$apply() uses try catch block internally to handle errors and if error occurs in one of the
watchers then it passes errors to $exceptionHandler service.
-The ng-repeat directive has a set of special variables which you are useful while
iterating the collection. These variables are as follows:
1) $index
2) $first
3) $middle
4) $last
- The $index contains the index of the element being iterated. The $first,
$middle and $last returns a boolean value depending on whether the current item
is the first, middle or last element in the collection being iterated.
The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the
root scope has one or more child scopes. Each view has its own $scope (which is a child of the root scope),
so whatever variables one view controller sets on its $scope variable, those variables are invisible to other
controllers.
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="myController1">
{{data.theVar}}
</div>
<div ng-controller="myController2">
{{data.theVar}}
</div>
<script>
var module = angular.module("myapp", []);
var myController1 = module.controller("myController1", function($scope) {
$scope.data = { theVar : "Value One"};
});
var myController2 = module.controller("myController2", function($scope) {
$scope.data = { theVar : "Value Two"};
});
</script>
</body>
</html>
This example contains two views, each with their own controller function. Each
controller sets the variable data.theVar to different values.
Root $scope
o $scope for myController 1
o $scope for myController 2
As you can see, the $scope object used by the two controllers are not the
same $scope object. That is also why the example above would write out two different
values for the data bindings {{data.theVar}} inside the two views. The two controller
functions for the views set different values for the data.theVar variable in each their
own $scope object.
You can think $rootScope as global variable and $scope as local variables
then we need to handle DOM events like mouse clicks, moves, keyboard presses,
change events and so on.
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
86-79
same
questions.
87. What is core module in AngularJS?
Module
A module is a collection of services, directives, controllers, filters, and configuration
information.angular.module is used to configure the $injector.
Then you can create an injector and load your modules like this:
However it's more likely that you'll just use ngApp or angular.bootstrap to simplify this
process for you.
Usage
angular.module(name, [requires], [configFn]);
Arguments
Returns
<input ng-click="toggledisplay()" />
Syntax for AngularJS double click event.
<input ng-dblclick="toggledbldisplay()" />
Example:
ng-click example:
Click the below button to Show/Hide the div and change the button text.
ng-dblclick example:
Double click the below button to Show/Hide the div and change the button text.
Source code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/D
-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body>
<div ng-app="SampleApp" ng-controller="SampleCntrl">
<ul class="exmpul">
<li><strong>ng-click example:</strong>
<br />
Click the below button to Show/Hide the div and change the button text.
<br />
<br />
<input type="button" ng-click="toggledisplay();" value="{{btntext}}" />
<br />
<br />
<div style="background: green; color: White; font-size: 20px; font-weight: bold;
padding: 10px;" ng-show="divdisp">
AngularJS Tutorial - Click event example.
</div>
<br />
</li>
<li><strong>ng-dblclick example:</strong>
<br />
Double click the below button to Show/Hide the div and change the button text.
<br />
<br />
<input type="button" ng-dblclick="toggledbldisplay();" value="{{btndbltext}}" />
<br />
<br />
<div style="background: green; color: White; font-size: 20px; font-weight: bold;
padding: 10px;" ng-show="divdbldisp">
AngularJS Tutorial- Double click event example.
</div>
</li>
</ul>
</div>
<script>
var myapp = angular.module("SampleApp", []);
myapp.controller("SampleCntrl", function ($scope) {
$scope.btntext = "Hide";
$scope.btndbltext = "Hide";
$scope.divdisp = true;
$scope.divdbldisp = true;
$scope.toggledisplay = function () {
if ($scope.btntext == "Hide") {
$scope.btntext = "Show";
$scope.divdisp = false;
}
else {
$scope.btntext = "Hide";
$scope.divdisp = true;
}
};
$scope.toggledbldisplay = function () {
if ($scope.btndbltext == "Hide") {
$scope.btndbltext = "Show";
$scope.divdbldisp = false;
}
else {
$scope.btndbltext = "Hide";
$scope.divdbldisp = true;
}
};
});
</script>
</body>
</html>
Constants
Why?: Provides a way to inject vendor libraries that otherwise are globals. This
improves code testability by allowing you to more easily know what the
dependencies of your components are (avoids leaky abstractions). It also allows
you to mock these dependencies, where it makes sense.
// constants.js
angular
.module('app.core')
.constant('toastr', toastr)
.constant('moment', moment);
})();
Use constants for values that do not change and do not come from another
service. When constants are used only for a module that may be reused in
multiple applications, place constants in a file per module named after the
module. Until this is required, keep constants in the main module in
a constants.js file.
Why?: A value that may change, even infrequently, should be retrieved from a
service so you do not have to change the source code. For example, a url for a
data service could be placed in a constants but a better place would be to load it
from a web service.
// Constants used by the entire app
angular
.module('app.core')
.constant('moment', moment);
Security
This document explains some of AngularJS's security features and best practices that you
should keep in mind as you build your application.
o $compile(userContent)
o $parse(userContent)
o $interpolate(userContent)
Sandbox removal
Each version of AngularJS 1 up to, but not including 1.6, contained an expression
sandbox, which reduced the surface area of the vulnerability but never removed it. In
AngularJS 1.6 we removed this sandbox as developers kept relying upon it as a security
feature even though it was always possible to access arbitrary JavaScript code if one
could control the AngularJS templates or expressions of applications.
Control of the AngularJS templates makes applications vulnerable even if there was a
completely secure sandbox:
https://ryhanson.com/stealing-session-tokens-on-plunker-with-an-angular-
expression-injection/ in this blog post the author shows a (now closed)
vulnerability in the Plunker application due to server-side rendering inside an
AngularJS template.
https://ryhanson.com/angular-expression-injection-walkthrough/ in this blog
post the author describes an attack, which does not rely upon an expression
sandbox bypass, that can be made because the sample application is rendering a
template on the server that contains user entered content.
It's best to design your application in such a way that users cannot change client-side
templates.
You can use suitably sanitized server-side templating to dynamically generate CSS,
URLs, etc, but not for generating templates that are bootstrapped/compiled by
AngularJS.
If you must continue to allow user-provided content in an AngularJS template then the
safest option is to ensure that it is only present in the part of the template that is made
inert via the ngNonBindabledirective.
HTTP Requests
Whenever your application makes requests to a server there are potential security issues
that need to be blocked. Both server and the client must cooperate in order to eliminate
these threats. AngularJS comes pre-configured with strategies that address these issues,
but for this to work backend server cooperation is required.
In compile phase the angular parser starts parsing the DOM and whenever the parser
encounters a directive it creates a function. These functions are termed as template or
compiled functions. In this phase we do not have access to the $scope data. In the link
phase the data i.e. ($scope) is attached to the template function and executed to get the
final HTML output.
Compile – It works on template. It’s like adding a class element in to the DOM (i.e.,
manipulation of tElement = template element), hence manipulations that apply to all
DOM clones of the template associated with the directive.
Link – It works on instances. Usually used for registering DOM listeners (i.e., $watch
expressions on the instance scope) as well as instance DOM manipulation. (i.e.,
manipulation of iElement = individual instance element).
Example
<div ng-app="">
<p ng-cloak>{{ 5 + 5 }}</p>
</div>
Try it Yourself »
AngularJS applications can make HTML documents flicker when the application is being
loaded, showing the AngularJS code for a second, before all code are executed. Use
the ng-cloak directive to prevent this.
Syntax
<element ng-cloak></element>
Parameter Values
95. Mention what are the styling form that ngModel adds to CSS classes ?
ngModel adds these CSS classes to allow styling of form as well as control
•ng- valid
•ng- invalid
•ng-pristine
•ng-dirty
ngif
----
===>The ng-if directive removes the HTML element if the expression evaluates to false.
===>If the if statement evaluates to true, a copy of the Element is added in the DOM.
===>The ng-if directive is different from the ng-hide, which hides the display of the
element,
where the ng-if directive completely removes the element from the DOM.
===>The ng-if directive will destroy (completely removes) the element or recreate the
element.
==>This directive can add / remove HTML elements from the DOM based on an
expression.
==>If the expression is true, it add HTML elements to DOM, otherwise HTML elements
are removed from the DOM.
Syntax:
==>ng-if, on the other hand, actually removes the element from the DOM
when the condition is false and only adds the element back once the condition turns
true.
------
<element ng-if="expression"></element>
Parameter Values:
----------------
Value Description
----- -----------
expression An expression that will completely remove the element if it returns false.
EXAMPLE:
-------
<!DOCTYPE html>
<html>
<body ng-app="">
<div ng-if="myVar">
<h1>Welcome</h1>
<p>Welcome to my if directive</p>
<hr>
</div>
<p>The DIV element will be removed when the checkbox is not checked.</p>
</body>
</html>
ng-repeat:
---------
Note: Each instance of the repetition is given its own scope, which consist of the current
item.
----
==>If you have an collection of objects, the ng-repeat directive is perfect for making a
HTML table,
displaying one table row for each object, and one table data for each object property.
Syntax:
------
<element ng-repeat="expression"></element>
-----------------
Value Description
----- ----------
x in records
Example:
-------
<!DOCTYPE html>
<html>
<script>
app.controller("myCtrl", function($scope) {
$scope.records = [
"Sachin Tendulkar",
"A.P.J Abdul Kalam",
"Abraham Lincoln",
"Nelson Mandela",
});
</script>
</body>
</html>
------------------------------
--------------------
==>The value of the ng-include attribute can also be an expression, returning a filename.
==>By default, the included file must be located on the same domain as the document.
Syntax
------
Parameter Values
----------------
Value Description
----- -----------
autoscroll Optional. Whether or not the included section should be able to scroll
AngularJS - Includes
---------------------
==>HTML does not support embedding html pages within html page.
Using Ajax − Make a server call to get the corresponding html page and
Using Server Side Includes − JSP, PHP and other web side server technologies can
Using AngularJS, we can embed HTML pages within a HTML page using ng-include
directive.
<div ng-app = "" ng-controller = "studentController">
</div>
==>By default, HTML does not provide the facility to include client side code from other
files.
==>
AngularJS Includes
--------------------
One of the most common ways is to include HTML code is via Javascript.
in an HTML page on the fly. Hence, Javascript can also be used to include code from
other files.
Server Side Includes
--------------------
Server Side Includes are also available for including a common piece
Page header
Page footer
Navigation menu.
Note:
-----
If the web server process does not have access to read the file or execute the script,
the include command will fail. The 'virtual' word is a keyword that is required
AngularJS Includes
------------------
compile and include an external HTML fragment in the main AngularJS application.
Summary:
--------
==>By default, we know that HTML does not provide a direct way to include HTML
content
==>Another way of including HTML content from other files is to use the
==>The virtual parameter keyword is used to denote the file which needs to be
embedded.
==>Angular also provides the facility to include files by using the ng-include directive.
This directive can be used to inject code from external files directly into the main HTML
file.
Example:
-------
<!DOCTYPE html>
<html>
<body ng-app="">
<div ng-include="'include.html'"></div>
</body>
</html>
include.html
-----------
<!DOCTYPE html>
<html>
<body>
<h1>Include Header..!!</h1><br><br>
<h5>This text has been included into the HTML page, using ng-include!</h5>
</body>
</html>
Templates
In AngularJS, templates are written with HTML that contains AngularJS-specific elements
and attributes. AngularJS combines the template with information from the model and
controller to render the dynamic view that a user sees in the browser.
These are the types of AngularJS elements and attributes you can use:
<html ng-app>
<!-- Body tag augmented with ngController directive -->
<body ng-controller="MyController">
<input ng-model="foo" value="bar">
<!-- Button tag with ngClick directive, and
string expression 'buttonText'
wrapped in "{{ }}" markup -->
<button ng-click="changeFoo()">{{buttonText}}</button>
<script src="angular.js">
</body></html>
In a simple app, the template consists of HTML, CSS, and AngularJS directives contained in
just one HTML file (usually index.html).
In a more complex app, you can display multiple views within one main page using "partials"
– segments of template located in separate HTML files. You can use the ngView directive to
load partials based on configuration passed to the $route service. The AngularJS
tutorial shows this technique in steps seven and eight.
100. Who created Angular JS ?
AngularJS was created, as a side project, in 2009 by two developers, Misko Hevery
and Adam Abrons. The two originally envisioned their project, GetAngular, to be an
end-to-end tool that allowed web designers to interact with both the frontend and
the backend.
Google.
One of the original creators, Adam Abrons stopped working on AngularJS but Misko Hevery
and his manager, Brad Green, spun the original GetAngular project into a new project,
named it AngularJS, and built a team to create an maintain it within Google.
One of AngularJS' first big wins internally at Google occurred when the company
DoubleClick was acquired by Google and they started rewriting part of their application
using AngularJS. Because of DoubleClick's initial success, Google seems to have invested
even more resources into Angular and has blessed AngularJS for internal and external
product usage.
Because of this, the Angular team inside Google has grown rapidly.
101. What is manual bootstrap?
If you need to have more control over the initialization process, you can use a manual
bootstrapping method instead. Examples of when you'd need to do this include using script
loaders or the need to perform an operation before AngularJS compiles a page.
Here is an example of manually initializing AngularJS:
<!doctype html>
<html>
<body>
<div ng-controller="MyController">
Hello {{greetMe}}!
</div>
<script src="http://code.angularjs.org/snapshot/angular.js"></script>
<script>
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.greetMe = 'World';
}]);
angular.element(function() {
angular.bootstrap(document, ['myApp']);
});
</script>
</body>
</html>
Note that we provided the name of our application module to be loaded into the injector as
the second parameter of the angular.bootstrap function. Notice that angular.bootstrap will
not create modules on the fly. You must create any custom modules before you pass them
as a parameter.
You should call angular.bootstrap() after you've loaded or defined your modules. You cannot
add controllers, services, directives, etc after an application bootstraps.
This is the sequence that your code should follow:
1. After the page and all of the code is loaded, find the root element of your AngularJS
application, which is typically the root of the document.
2. Call angular.bootstrap to compile the element into an executable, bi-directionally
bound application.
102. What is Auto bootstrap?
<!doctype html>
<html ng-app="optionalModuleName">
<body>
I can add: {{ 1+2 }}.
<script src="angular.js"></script>
</body>
</html>
AngularJS is an open source web application framework. It was originally developed in 2009
by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is
1.4.3.
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 currently have to write. And it all happens within the
browser, making it an ideal partner with any server technology.
Features
AngularJS is a powerful JavaScript based development framework to create RICH
Internet Application(RIA).
Overall, AngularJS is a framework to build large scale and high performance web
application while keeping them as easy-to-maintain.
Core Features
Following are most important core features of AngularJS −
Scope − These are objects that refer to the model. They act as a glue between
controller and view.
Controller − These are JavaScript functions that are bound to a particular scope.
Services − AngularJS come with several built-in services for example $https: to make
a XMLHttpRequests. These are singleton objects which are instantiated only once in
app.
Filters − These select a subset of items from an array and returns a new array.
Templates − These are the rendered view with information from the controller and
model. These can be a single file (like index.html) or multiple views in one page
using "partials".
Model View Whatever − MVC is a design pattern for dividing an application into
different parts (called Model, View and Controller), each with distinct
responsibilities. AngularJS does not implement MVC in the traditional sense, but
rather something closer to MVVM (Model-View-ViewModel). The Angular JS team
refers it humorously as Model View Whatever.
Deep Linking − 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.
AngularJS has no dependency on jQuery library. But it can be used with jQuery
library.
If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not
available, angular.element delegates to AngularJS's built-in subset of jQuery, called "jQuery
lite" or jqLite.
jqLite is a tiny, API-compatible subset of jQuery that allows AngularJS to manipulate the
DOM in a cross-browser compatible way. jqLite implements only the most commonly
needed functionality with the goal of having a very small footprint.
To use jQuery, simply ensure it is loaded before the angular.js file. You can also use
the ngJq directive to specify that jqlite should be used over jQuery, or to use a specific
version of jQuery if multiple versions exist on the page.
105.What is injector?
$injector
$inject Annotation
The $inject property
If a function has an $inject property and its value is an array of strings, then the strings
represent names of services to be injected into the function.
// Given
var MyController = function(obfuscatedScope, obfuscatedRoute) {
// ...
}
// Define function dependencies
MyController['$inject'] = ['$scope', '$route'];
// Then
expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
Example:
<html>
<body>
<div ng-app=””>
Name: {{ “angular”+”js”}}
</div>
</body>
</html>
2. ng-init – This is used to initialize application data. Sometimes you may require some
local data for your application, this can be done with the ng-init directive.
Example:
<html>
<body>
</div>
</body>
</html>
3. ng-model – And finally we have the ng-model directive, which is used to bind the
value of an HTML control to application data. The example below shows how to use the
ng-model directive.
In this example,
We are going to create 2 variables called "quantity" and "price". These variables are
going to be bound to 2 text input controls.
We are then going to display the total amount based on the multiplication of both
price and quantity values.
.
<html>
<body>
</div>
</body>
</html>
Filters are used to change modify the data and can be clubbed in expression or directives
using pipe character. Following is the list of commonly used filters.
uppercase filter:
Add uppercase filter to an expression using pipe character. Here we've added uppercase
filter to print student name in all capital letters.
Example:
lowercase filter
Add lowercase filter to an expression using pipe character. Here we've added lowercase
filter to print student name in all lowercase letters.
Example:
currency filter
Add currency filter to an expression returning number using pipe character. Here we've
added currency filter to print fees using currency format.
Example:
filter filter
To display only required subjects, we've used subjectName as filter.
Example:
orderby filter
To order subjects by marks, we've used orderBy marks.
Example:
Subject:
<ul>
<li ng-repeat = "subject in student.subjects | orderBy:'marks'">
{{ subject.name + ', marks:' + subject.marks }}
</li>
</ul>
1. AngularJS will work with the latest versions of Chrome, Firefox, Safari, and Opera, as well
as Internet Explorer version 8, 9, and 10. You will need to do some extra work for IE8
2. To make AngularJS Work with IE8 use the following
<html ng-app="application_name" id="application_name">
Though ng-app="application_name" is sufficient for the other browsers as mentioned in
point 1; for IE 8, id attribute is also required
3. We cannot make IE to recognize and include templates in the following manner
<ng-include="'myInclude.tpl.html'"></ng-include>
Though, we can take a different strategy to make IE8 recognize and include templates by
using
<div ng-include="'myInclude.tpl.html'"></div>
we have to make IE8 recognize <ng-include=""> to be able to use this custom tag to include
templates. We can do that by using
<head>
<!--[if lte IE 8]>
<script>
document.createElement('ng-include');
document.createElement('ng-view');
...
<![endif]-->
</head>
4. Supporting IE7 for AngularJS
You need to do everything that you did for IE8.
AngularJS was not tested with IE7; so you need to adjust stuff as they come along
IE7 does not have many APIs commonly present in web-browsers such as JSON API
You will need libraries such as http://bestiejs.github.io/json3/ to be included in your
application to support JSON
5. IE6 is not supported
A Service ia a reusable singleton ovject which is used to organize and share code across
your app. A Service can be injected into controllers,filters,directives.
1. Service
2. Factory
3. Provider
4. Value
5. Constant
Scope is a JavaScript object refers to the application model. It acts as a context for
evaluating angular expressions. Basically, it acts as glue between controller and view.
Scope are hierarchical in nature and follow the DOM structure of your AngularJs app.
AngularJs has two scope objects: $rootScope and $scope
--> if view interacting with the controller,such type of angular application called as
"DYNAMIC ANGULAR APPLICATION".
index.html
---
<html>
-------
-------
-------
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"/>
</html>
step-2: declare the logical name for web application by using 'ng-app' directive.
eg:
<html ng-app="app">
--------
--------
</html>
eg:
<html ng-app="app">
<div ng-controller="ctrl">
--------
--------
</div>
</html>
var obj=angular.mpdule("app",[]);
obj.controller("ctrl",function($scope){
$scope.var_one="angularjs";
$scope.var_two="angular 2";
});
view doesnot interacting with the controller such type of angular applications are called
"STATIC ANGULAR APPLICATIONS".
116.What is ng-app?
Example: on the <body> or <html> tags.
only one AngularJS application can be auto-bootstrapped per HTML document. The
first ngApp found in the document will be used to define the root element to auto-
bootstrap as an application. To run multiple applications in an HTML document you
must manually bootstrap them using angular.bootstrap instead.
AngularJS applications cannot be nested within each other.
Do not use a directive that uses transclusion on the same element as ngApp. This
includes directives such as ngIf, ngIncludeand ngView. Doing this misplaces the
app $rootElement and the app's injector, causing animations to stop working and
making the injector inaccessible from outside the app.
You can specify an AngularJS module to be used as the root module for the application. This
module will be loaded into the $injectorwhen the application is bootstrapped. It should
contain the application code needed or have dependencies on other modules that will
contain the code.
AngularJS is known for creating dynamic web apps because of its feature of extending
HTML syntax according to your application components. Other than that, it also provides a
wide range of other prominent features like two way data binding, templates, MVC,
dependency injection, directives, testing, and a lot more to build almost any kind of web
app.
AngularJS alone can’t create a web app. You need a lot of other technologies also,
compatible with AngularJS to create a complete web app – say – backend, frontend,
deployment technologies. So, in order to create a completeweb app, you need to atleast
have a bit of knowledge of such other technologies as well.
1.model
2.view
3.controller
1) Model - Model represents an object or JAVA POJO carrying data. It can also have
logic to update controller if its data changes.
2)View - View represents the visualization of the data that model contains.
---------------------------
(1).asp.net mvc provides clean seperation of concerns,so easy code maintainance will be
possible.
(3).asp.net mvc provides complete control over html,javascript,and css.this allows proper
integration of latest web technologies like html5,css3,jquery,angular js.
(4).asp.net mvc supports built in support for url-routing.,this supports method based
execuition .
In AngularJS the MVC pattern is implemented in JavaScript and HTML. The view is defined in
HTML, while the model and controller are implemented in JavaScript. There are several ways
that these components can be put together in AngularJS but the simplest form starts with the
view.
Views
The view in an AngularJS application is created with HTML. By using a simple example, we can
see that HTML can all exist inside a single page. However, almost all applications will quickly
move past the single view model; in this case the fragments of HTML that make up the view will
be stored in individual files. Take this HTML page as a starting point:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="utf-8" />
</head>
<body>
<div id="messageTitle"></div>
<div id="message">Hello World</div>
</body>
</html>
At this point, it’s easy to consider this entire HTML document to be the view since there’s only
one. However, because this is a Single Page Application, only a portion of the page represents
the current view. In this case, the contents of the body represent the view while the HTML and
HEAD elements make up the container for the individual views. In AngularJS it’s also popular to
mark a specific element in the page as the view giving you more control over which portions of
the page make up the container and which make up the changing view.
<!DOCTYPE html>
<html>
<head>
<title>Hack Hands Angular - Demos</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Hack Hands Angular Demos</h1>
<div ng-view>
<div id="messageTitle"></div>
<div id="message">Hello World</div>
</div>
</body>
</html>
This HTML is not yet a functioning AngularJS view. There are a couple of steps required to
include and bootstrap the AngularJS framework
Referencing the AngularJS framework is a simple matter of adding a script tag referencing the
framework script on a Content Delivery Network (CDN).
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
When AngularJS loads it will see this directive which will cause it to look for a module named
“hackApp.” Modules are a key component of AngularJS that we’ll cover in more detail in a
follow-up post. For now, it’s enough to know this view needs to be able to reference a module
representing the AngularJS
120.what is mvc?
1.model
2.view
3.controller
1) Model :An architecture for building applications that separate the data (model) from
the user interface (view) and the processing (controller). In practice, MVC views and
controllers are often combined into a single object because they are closely related..
2)View - The view displays the model data, and sends user actions (e.g. button clicks)
to the controller. The view can:
be independent of both the model and the controller; or
actually be the controller, and therefore depend on the model.
.
3)Controller The controller provides model data to the view, and interprets user
actions such as button clicks. The controller depends on the view and the model. In some
cases, the controller and the view are the same object.
---------------------------
(1).asp.net mvc provides clean seperation of concerns,so easy code maintainance will be
possible.
(3).asp.net mvc provides complete control over html,javascript,and css.this allows proper
integration of latest web technologies like html5,css3,jquery,angular js.
(4).asp.net mvc supports built in support for url-routing.,this supports method based
execuition .
AngularJS expressions are much like JavaScript expressions, placed inside HTML
templates by using double braces such as: {{expression}}. AngularJS evaluates
expesssions and then dynamically adds the result to a webpage. Like JavaScript
expressions, they can contain literals, operators, and variables.
Example:
{{1+2}}
{{x+y}}
{{x==y}}
{{x=2}}
{{user.id}}
123. what are directives in angularjs? What are different ways to invoke a directive?
AngularJS directives are used to extend the HTML vocabulary i.e they decoreate html
elements with new behaviours and help to manipulate html elements attributes in
interesting way.
There are some built –in directives provided by AngularJS like as ng-app, ng-controller, ng-
repeat, ng-model etc.
There are four methods to invoke a directive in your angular app which are equivalent.
Method Syntax
As an attribute <span my-directive></span>
As a Class <span class=”my-directive:
expression;”></span>
As an element <my-directive></my-directive>
As a comment <!—directive: my-directive expression-->
AngularJS has no dependency on JQuery library .But it can be used with jQuery
library.
125. What IDE'S are currently used for the development of angularjs?
o Eclipse
o Visual Studio
o WebStorm
o TextMate
o SublimeText
o Atom
o Visual Studio Code