48
Angular JS

Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Embed Size (px)

Citation preview

Page 1: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Angular JS

Page 2: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Contents• About Angular JS• Hassle free Angular JS• MVC pattern of Angular JS• Example of MVC pattern• Data binding• Applying CSS dynamically• Templates• Filters• Form controls• Mark Up• Enable and Disable Html form

elements• Custom Directives• Example of custom directives• Dynamic generation of Elements• Validation in Html• $ Watch in Angular JS• $broadcast and $emit in Angular JS

2

• Include one html code into another in Angular JS• ngCloak in Angular JS• Hiding and Displaying the Element • Routing in Angular JS• Git Basics• Factors in Angular JS• Service in Angular JS• Routing in Angular JS• Provider in Angular JS• Example for Provider• Controller in Angular JS• Do’s and Don'ts in Controller• Scopes in Angular JS• ng Model• Angular for Mobile Application• Routing in Angular JS• Unit Test Runner – Karma JS• Sample Unit test runner test case using KARMA

Page 3: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• AngularJS is a structured framework for dynamic web applications

• It extends the normal HTML syntax to express the application component more clearly.

• The data binding and dependency injection reduces much of the code and makes it more precise. All these things happen within the browser without using any server side language.

About AngularJS

3

Page 4: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

4

• The Complete Client Side Solution: AngularJS provides the essential features to build a CRUD (Create

Read Update Delete) app in a cohesive set: data-binding, basic templating directives, form validation, routing, deep-linking, reusable components, dependency injection.

Testability: unit-testing, end-to-end testing, mocks, test harnesses are embedded.

About AngularJS contd…

Page 5: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• Registering Callbacks : Java script callbacks clutters your code whereas, AngularJS vastly reduces the code size. It makes it easier to see what your application does.

• Manipulation of HTML DOM : In AJAX based application DOM(Data Object Model) manipulation is complex and error prone. AngularJS never has to manipulate the DOM programmatically, it can be done if it is needed.

Hassle Free Nature

5

Page 6: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

6

• Arrange data to and from the UI : AngularJS assembles the data from server to the HTML objects and allows the user to modify, validate, display validation errors and returns the object back to server. In this process lot of boilerplate code is reduced.

• Writing tons of initialization code just to get started : To initiate an

AJAX app the user has to write a lot of code. But in the case of AngularJS it can be started easily using services and dependency injection.

Hassle Free Nature contd…

Page 7: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• AngularJS implements the most efficient MVC frame work.• It inherently splits your application to MVC Pattern. MVC Frame Work:• M - Model - The models are the objects that are from the rest API or

any javascript objects. The API may provide json or XML and can be parsed by javascript.

• V - View - The views are nothing but the HTML elements or the directives which are the elements of DOM. The view can be dynamically changed based on the model.

MVC pattern of Angular JS

7

Page 8: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• C - Controller - Generally the business logic will be the part of the controller.

• MVW(Model View Whatever)- The view in this model is changed as soon as the it is changed without the DOM access. In Angularjs it is called as MV-VM frameworks. Controller bridges between the model and the view.

• This could be easily understood by a simple calculator program given below. We could see that even without DOM access business logic is applied.

8

MVC pattern of Angular JS contd…

Page 9: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• As soon as the user clicks on the calculate button in the view, the user can view the result.

The Template or the HTML code : <div ng-controller="Calculator"> Enter a value : <input ng-model="num1"

type="text"> Another Value: <input ng-model="num2"

type="text"> Operator: <select ng-model="operation" ng-

options="operator for operator in operators"></select> <button ng

click="calculate()">Calculate</button> <br><br>

Result: {{result}}

• Applying business logic without DOM access.

Angular JS Code: function Calculator($scope) { $scope.operators = ['+', '-', '*', '/']; $scope.operation = $scope.operators[0]; $scope.calculate = function() { var X = parseInt($scope.num1); var Y = parseInt($scope.num2); var res = 0; switch ($scope.operation) { case '+': res = X + Y; break; case '-': res = X - Y; break; case '*': res = X * Y; break; case '/': res = X / Y; break; } $scope.result = res; };}

Example: Simple Calculator program

Page 10: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

10

MVC Pattern in AngularJS

Page 11: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript • Here we cannot achieve two way data binding. ( i.e)

changes to the model or the view are not automatically reflected in the view or model.

• Developer has to sync the view with model and the model with view by parsing the DOM element every time.

Example:<div><input type = “text” id = “username” onblur = “updateUI()”>User Name :<span id = “user_name”></span></div><script>function userInfo(){ // To set the value document.getElementById(“username”).value() = “Foo”;}function updateUI(){var uname= document.getElementById(“username”).value() ;document.getElementById(“user_name”).value = uname;}</script>

Angular JS • It supports two way data binding. Binding with view

to model or model to view can be done automatically once the user interact s with the UI or the changes in the model.

• There is no DOM parsing done here. It can be achieved by accessing the model of the corresponding control in the form

Example:<div ng-controller = “userInfo”> <input type = “text” ng-model = “username”> // Dynamically change on the value based on the user input User Name :<span ng-bind = “username”></span></div><script>function userInfo($scope){ // To set the value $scope.username = “Foo”; }</script>

Data Binding

Page 12: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript HTML DOM Style Object allow us to dynamically set the CSS using the java script code.

Example:<button onclick=”switchBorder();”>Click

me</button><div id=”changeBorder”>

On click event border color changes </div>

function switchBorder ()

{var element = document.getElementById(changeBorder);element.style.border = ‘1px solid red’;

element.style.color = ‘#FFF’;}

AngularJSThe ngClass and ngStyle directive allows us to dynamically set CSS classes on a HTML element by databinding an expression.Example:.red{ border: 1px solid red; color: #FFF;}

<div ng-controller="MainCtrl"><button ng-click="setcolor = !setcolor">Click

Me</button> <div ng-class="{red: setcolor}"> On click event border color changes </div>

</div>

Since everything is taken care in the template,

nothing is required inside the controller

Applying CSS dynamically

Page 13: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript

Needs more user defined functions to achieve the following special types of elements & attributes.

• Filters - User defined functions are needed to format the data in GUI(Graphical User Interface).

• Form Controls - Use of third party libraries or Customized functions are needed to support the validation feature.

• Directives -There are no predefined functions required to reuse the DOM Component.

• Mark up - DOM parsing is needed to bind the data in UI(User Interface).

Angular

We can use the following types of angular elements & attributes

• Filters - Formats data to display• Form controls - Validates user input• Directives - represents a reusable

DOM component.• Mark up - The double curly brace

notation {{ }} to bind expression to elements

Templates

Page 14: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript• In JS to format the data, we need to write our own

user defined functionsExample:<div>

Current Date : <span id = “cDate”></span></div><script>function dateFormat(){ var currDate; var currTime; var date = new Date().getTime(); currDate = date.getDate() + ‘-’ + (date.getMonth() + 1) +

date.getFullYear(); currTime = date.getHours() + ‘:’ + date.getMinutes() + ‘:’

+ date.getSeconds(); document.getElementById(“cDate”).value = currDate + ‘

’ + currTime;}</script>

Angular• AngularJs provides lot of options to format

the data• No need to write user defined functions to

format the data Example:<div ng-controller = “dateFormat”>

Current Date : <span>{{date | date:'dd-MM-yyyy HH:mm:ss'}}</span>

</div>

function dateFormat($scope){

$scope.date = new Date().getTime();}

Filters

Page 15: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript • Validation of form controls can be achieved by writing a

separate user defined function for each control element in the form.

• Another way is by using a third party library, we can achieve the validation.

• Hiding and showing of the validation messages can be done by applying style for the corresponding element

Example:<form name = “userinfo”> Name : <input type = “text” ng-model = “name” id =‘uname’ onblur = “userNameValidation()”> <span id = “uName”>This field is required!</span></form>//Take the value from the template during onblur() and

validates. <script> function userNameValidation(){ var userName =

document.getElementById(“uname”).value; if (userName != “”) document.getElementById(“uname”).style.display = ‘block’; else document.getElementById(“uname”).style.display = ‘none’; }</script>

Angular• By default, validation of form controls can be taken care by

angularjs.• There is no need of third party libraries.• There is no need to apply styles for each validation message

container.Example:<form name = “userInfo”>

Name : <input type = “text” ng-model = “name” name = “uname” required>

<span ng-show = “userInfo.uname.$error.required”>This field is required!

</span>Last Name : <input type = “text” ng-model = “lastname” name =

“lname” ng-maxlength = “10” ><span ng-show = “range.size.$error.integer”>This is not a valid

integer! </span><span ng-show = “range.size.$error.maxlength”>Too

Large</span></form>

Note: The keywords like required,maxlength can beused as an attribute in the element to achieve the required form validation.

Form Controls

Page 16: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript• To update the UI, we need to write our own

function to parse the DOM element and update the data for the corresponding DOM element.

Example:<div>Enter your Name: <input type = “text” id = “uinfo” onchange =

“updateUserInfo()”/>Name : <span id = “updateinfo”></span></div><script>function updateUserInfo(){ var name =

document.getElementById(“uinfo”).value; document.getElementById(“updateinfo”).value =

name;}</script>

AngularJs• AngularJs provides double curly brace notation

{{ }} or ng-bind to bind expression to elements.• It automatically updates the UI based on the

change in model. Example:<div> Enter your Name : <input type = “text” ng-model =

“uinfo” /> Name : <span>{{uinfo}}</span></div>

Note : Model gets binded with the view (UI) without parsing the DOM

Mark Up

Page 17: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript• Enabling and Disabling the element is done

through its HTML ID’s or Classes.

Example:In the HTML file

Click me to toggle: <input type="checkbox“ onclick="enableDisable(this.checked)"> <button id="buttonId">Button</button> In the JavaScript file function enableDisable(bEnable) { document.getElementById(buttonId).disabled = !b Enable;}

Angularjs• The ngDisabled directive allows us to enable

and disable the HTML elements without referring its classes or IDs.

• Mapping check box model object to ng-disabled attribute in the <button> tag. If checkbox is checked, model object will be updated with true else false value. Whenever model object holds true value the button gets disabled automatically otherwise it is enabled.

Example:<div ng-controller = “mainController()”>

Click me to toggle: <input type="checkbox" ng-model="checked"><br/><button ng-disabled="checked">Button</button>

</div>Note:No explicit code needs to be written inside the controller since it is handled inside the model itself.

Enable and Disable HTML form elements

Page 18: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• Custom Directive is an exclusive feature of angularjs. Directives are the markers on DOM element, which will attach a specific behaviour to the HTML element and its children. Using directives the user is able to decorate the elements and manipulate DOM in different ways. A directive may be a HTML element, attribute, class and even a comment.

• Directives are 2 types, predefined and user-defined. i) Pre-defined directives - ngBind, ngRepeat, ngView etc. ii) User-defined directives - User can name his own directive based on the application e.g.: myDirective

Custom Directives

18

Page 19: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

19

• The directives can be used wherever the functionality is repeated more than once. This can reduce the code size and code duplication. The user has to just attach the created directive name in the HTML file wherever necessary.

• When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as an integer. Directives with greater numerical priority are compiled first. The order of directives with the same priority is undefined. The default priority is 0.

Custom Directives contd…

Page 20: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

In html, it is enough to mention the directive name

either as an element,attribute,comment or class.

In this example it is declared as an element.

Html:

<!DOCTYPE html>

<html ng-app="myapp">

<head>

<meta charset="utf-8" />

<title>User Form</title>

</head>

<body ng-controller="MainCtrl">

<form-directive><form-directive/>

</body>

</html>

Note: Here the <form-directive> element is replaced by the template mentioned in the Directive.

AngularJs Script:var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) { $scope.name = 'World';});

app.directive('formDirective',function(){ return { replace:true, restrict: 'AE', template: '<ul>' + '<li>Name <input type ="text"></li>' + '<li>Age<input type ="text"></li>' + '<li>Country<input type ="text"></li>' + '<li>Email<input type ="text"></li>' + '</ul>', }});

Example for Custom Directive

• Here is an example of a common input form directive. In an application, if the user is in need of the

form details, the user has to define only the directive name in the desired place.

Page 21: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

JavascriptIn javascript, developer has to get container id and create the html elements as string value and then append to DOM container.

Example:<button onclick=”addNewField()” >Add

New</button><div id=”fields_container‘’></div>

var field_element = document.getElementById(“fields_container‘’);

function addNewField() { field_element.innerHTML = field_element.innerHTML +‘<br>’+ ‘<label>Mobile Number: </label>+ <input type=”text” name=”mobileNumber”>’;}Note: Here we need the element id or the class name to add the new element.

AngularjsIn angularjs,there is no need of container reference and no need to append to DOM. Directly map model object to ng-repeat.

Example:<div ng-controller = “templateController”>

<button ng-click = “addNewField();”>Add New</button><div ng-repeat = “option in formTemplate.options” >

<label>Mobile Number: </label><input type = “text” name=”mobileNumber” ng-model = “option.value”>

</div> </div>function templateController($scope) {

$scope.formTemplate.options = [];$scope.addNewField = function() {

$scope.formTemplate.options.push( { "value":"I am new element"} );

};}// DOM elements are not been created in controller.

Dynamic generation of elements

Page 22: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript

• In javascript ,we need to write a separate function for the input fields or use any third party validators for checking the form validity.

Example:<form name="myForm">First name: <input type="text" name="userName">Second Name: <input type="text" name="secName"> <button onclick ="submitForm()"></button></form>

function submitForm(){var usrName =document.forms["myForm"]["userName"].value;var secName=document.forms["myForm"]["secName"].value;if (usrName==null || usrName ==""){alert("First name must be filled out"); return false; }if(secName.length >= 10)alert(“Second Name should be less than 10 chars”);return false;// Submit POST logic here}Note: We should perform logical operations to validate the field

Angularjs

• By default angularjs supports the form validationinternally and provides css based formvalidities like ng-valid, ng-invalid, ng-pristine and ng-dirty.

• The user doesn’t have to add a third party library or write separately in the js file.

• The user can also add the validators in the directives make it even more optimized.

Example:<form name="myForm">

First name: <input type="text" name="userName" required ><p ng-show="myForm.userName.$invalid && !

myForm.userName.$pristine" class="error-message">You name Sis required.</p>

Second Name: <input type="text" name="secName" ng-maxlength > "10">

<p ng-show="userForm.secName.$error.maxlength" class="error-message">Username is too long.</p>

<button ng-disabled =” myForm.$invalid” ng-click "submitForm()"></button>

</form>

Note: Here it is enough to mention the min and the max values in the attribute.

Validation in HTML

Page 23: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript

• In Javascript,it is difficult to watch any object or

variable when it undergoes any changes .

• We need to update the values in the DOM

when the changes are done in any object or

variable.For example:

Html:

<input type=”text” id=”Example1” />

<input type”text” id=”Example2” />

JS:

var ele= document.getElementById(‘#Example1’).value;

document.getElementById(‘#Example2”).value(ele);

AngularJS

• In AngularJs there is a service called $watch to

watch any given object or variable. So it easily

identifies the changes whenever they are made

in the object or variable.

Syntax:

$watch(‘Example1’,function(){...});

For Example:

Html:

<input type=”text” ng-model=”Example1”>

<input type=”text” ng-model=”Example2”>

AngularJs

$watch(‘Example’,function(n,o){ $scope.Example2 =

n});

where n=New value, o= old value.

Note: $watch returns a de-registration

function for the registered listener.

$watch in AngularJS

Page 24: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript• In Javascript, there is no concept called

broadcasting• In Javascript it is not possible to call the local

functions of one module in some common component module . If we have to call then we need to make the function as global.

Example:function Example1(){ if(a == b) Example2(...) }function Example2(..){……...}

AngularJS• In AngularJS, there is an option to broadcast

the event name to the listeners of the event name once the particular event is completed.

• $broadcast : Dispatches an event name

downwards to all scopes.

• $emit : Dispatches an event name upwards to

all the scope.

• $on: The $on service is used for registering the

listener.

Example:function Example1(){ if(a == b) $broadcast(‘eventname’,[....]); }function Example2(){...}$on(‘‘eventname’,function(event,args)

{ Example2()});

$broadcast and $emit in AngularJS

Page 25: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript

• In Javascript, we need to make use of other

scripts or language to include one html code

into another html code.

Example:

• If one html file needs to be included in

another html file, then there is no way to

include it using javascript.

AngularJS

• In AngularJS, there is a way to include one

html file into another html file using ng-

include.

For Example:

Example1.html

<html>.....</html>

Exapmple2.html

<html>

<div ng-Include src=”../Example2.html”>

</html>

ngInclude in AngularJS

Page 26: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript

• In Javascript, there is no easy way to prevent

the template being displayed by the browser

before getting all the required data for that

template.

Example:

• We need to use the setTimeout function in

Javascript to periodically check whether all the

required datas are obtained. If all datas are

received then we need to display the contents.

AngularJS

• In AngularJS, ngCloak directive is used to

prevent the angular html template before

the compilation time.

For Example:

Html:

<div ng-cloak>

…...

</div>

Note:

• Once all the required informations are

obtained to build the DOM, ng-cloak attr

will be removed automatically from the

template.

ngCloak in AngularJS

Page 27: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript• In Javascript, if we want to hide or show an

element then we need to identify the element and set its display as ‘none’ or ‘block’.

For Example:

HTML

<div id=”Example1”></div>

JS

document.getElementById(‘#Example1’).css(‘display

’none);

(or)

document.getElementById(‘#Example1’).css(‘display

’, block);

AngularJS• In AngularJs, it is very easy to hide or show

elements than Javascript. It is enough to make one variable true or false to display or hide. This is achieved using ng-show and ng-hide. DOM access is not required.

For Example:

HTML<div ng-show=”Displaythecontent”><div ng-hide=”Hidethecontent”>

AngularJS$scope.Displaythecontent = true // For Showing$scope.Displaythecontent = false // For Hiding$scope.Hidethecontent = true // For Hiding$scope.Hidethecontent = false // For Showing

Hiding and Displaying the Element

Page 28: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript

• In Javascript, we need to write a separate code for navigation when the back or forward button is clicked in the browser.

AngularJS

• AngularJS have inbuilt router.• When back or forward button is clicked in the

browser, the control will automatically navigate to the corresponding page in AngularJS using $route service.

• $route service in AngularJS keeps watching on the location path continuously.once there is any change in the location path, it will map the path correspondingly.

• $routeprovider from $route service will take care of all the route changes.

• $routeProvider works in conjunction with the ngView. ngView will be updated with the response from the $routeProvider.

Example:If url path is /index, then$routeProvider.when(‘/index’,function(){

templateUrl: ../../urlpathcontroller: controllername

})• In this way we can define for all the url paths with the

corresponding template url and controller name.

Routing in AngularJS

Page 29: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• In AngularJS, the common code can be used across all the module controllers with the help of services i.e. we can use services across the app.

• It should be added as a dependency for the component.• AngularJs services are

Lazy instantiated - AngularJs only instantiates a service when an application component depends on it.

Singletons - Each Component dependent on a service gets a reference to the single instance generated by the service factory.

• Most often used services in AngularJs are Factory Service Provider

Git Basics

29

Page 30: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• A Factory is responsible for creating and returning an object that can be used to work with data, validate business rules, or perform a variety of other tasks. Angular factories are singletons by default.So the object returned by a factory is re-used by the application.

• When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Syntax:module.factory( 'factoryName', function );Example:Factory:Example.factory(Example1, function() { return { Exobject: function() { return "Factory Executed!!!!" } };});

Factories in AngularJs $

30

Output:Factory Executed!!!!

Controller:function Excontroller(Example1,$scope...){

……var a =

Example.Exobject();console.log(a);…….

}

Page 31: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• When declaring serviceName as an injectable argument you will be provided with an instance of the function.

Syntax:

module.service( 'serviceName', function );

Example:

Service:

Example.service(Example1, function() {

this.Exobj = function() {

return "Service executed!!!!”

};

});

Service in AngularJS

31

Output:Service executed !!!!

Controller:

function

Excontroller($scope,Example1

..){

….

var a = Example1.Exobj();

console.log(a);

….

}

Page 32: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Javascript• In Javascript, we need to use some custom

types for achieving the object oriented concepts.

Example:

var Example1 = function()

{

this.Example2 = ‘Sample Text’;

}

var Example3 = new Example1(); // Creating a

instance

var Example4 = Example3.Example2; // Getting the

value

AngularJS• In AngularJS, We can use service for achieving

the object oriented concepts. Whenever service is called it will return the instance object.

• Service are singleton in Angularjs.

Example:

Services.js

Example1.service(‘Servicename’,function(){

this.Getname = function()

{

…..

}

});

Controller.Js

function controllername(‘Servicename’,function(){

var Example2 = Servicename.Getname();

});

Routing in AngularJS

Page 33: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

● When declaring providerName as an injectable argument you will be provided with

ProviderFunction().$get(). Where,ProviderFunction - Is the function reference passed to the Provider

● The constructor function is instantiated before the $get method is called.

Syntax: module.provider( 'providerName', function );

Provider in AngularJS

33

Page 34: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Provider.js

Example.provider(Example1, function() {

this.$get = function() {

var name = this.name;

return {

sayHello: function() {

return "Hello, " + name + "!!!!"

}

}

};

this.setName = function(name) {

this.name = name;

};

});

Example For Provider:

34

Output:Hello,AngularJS!!!!

Controller:function Excontroller($scope, Example1,..){

…..…..

Example1.setName(‘AngularJS’);

var a = Example1.sayHello();

console.log(a);…..

…..}

Page 35: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Controller in AngularJS

• In AngularJs, a controller is a JavaScript constructor function that is used to augment the Angular Scope.

● Controller is attached to the DOM via the ng-controller directive.● Controller should contain only the Business Logic.

Example: Template <div ng-controller=”ExampleController”>

…… </div> Controller function ExampleController($scope,$timeout,....){ …. ... }

35

Page 36: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Do’s in Controller :1. Initialize a $scope object.2. Add a behaviour to the $scope object.

Don’ts in Controller :1. Don’t do any DOM manipulation in the controller. Directives can be used for DOM manipulation. 2. Don’t format input in controllers. Use Angularjs form controls instead.3. Don’t share states across the controllers. Services can be used for sharing across the app.4. Don’t filter the output. AngularJs Filters will do this operation.

Do’s and Don'ts in Controller

36

Page 37: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

1. Scope is an object that refers to the application model.

2. It connects the view with the controller. For Example: Template: (View)

<input ng-model=”Scopevariable”> Controller:

$scope.Scopevariable = “ScopeExample” ;

3. Scopes can be nested to limit access to the properties. For Example: A Parent scope cannot access the variable in a Child scope.

Scopes in AngularJS

37

Page 38: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

38

4. An app will contain one $rootscope and many childscope.

5. $rootscope - The object or variable which are attached to the $rootscope will be accessible across the app. We can assign a variable or object to the rootscope from any module. For Example: $rootscope.exampleVariable = “Example for Rootscope” $rootscope.exampleObject = “Example for Rootscope object” In this way we can assign anything to the $rootscope. Not every object or variable should be attached to the $rootscope, only those variable or objects which are needed across all the module should be attached to the scope.

Scopes in AngularJS

Page 39: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

6. Childscope - AngularJS components will automatically include the ng-scope class to it to perform the operation. These are nothing but the child scope. For Example: Controller $scope.examples = [example1,example2,example3]; Html <div ng-repeat=”example in examples”> {{example}}</div> When we inspect element in the browser, it will look like the following <div ng-repeat=”example in examples” ng-scope>example1</div> <div ng-repeat=”example in examples” ng-scope>example2</div> <div ng-repeat=”example in examples” ng-scope>example3</div>

39

Page 40: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

40

7. A child scope will automatically inherit from their parent scope. It follows the prototypal inheritance. For Example: <div>{{Prototypal_Inheritance}}</div>• When AngularJs evaluates this expression, it looks for this variable in

the scope associated with it. • If this variable is not present in its scope, then angular will search

this variable in its parent scope and binds the value.• The search will expand till the rootscope when the variable is not

available in the corresponding scope and its parent scope. This property is called prototypal inheritance.

8. Scopes can watch expression and propagate events.

Page 41: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

9. Scope will call $apply() method to display the modified content in the view.

10. $apply() method will call $digest() method to get the list of modified scope variables.

11. $digest() method will make use of $watch() method to identify the modified values. $digest method will check all the watched expression list with their previous value.

12. The another type of scope other than child scope and rootscope is isolated scope.

13. Isolated scope - Isolated scopes are the scopes which will not have an access to their parent scope properties. These kind of scopes can be created using directives. In directives there is a concept called DDO(Data Definition Object) which are nothing but the attributes which are sent to the directives for their operations. scope is one of the DDO options where we can set true or false. If we set true, then the directive will create a isolated scope. Isolated scope will not follow the prototypal inheritance. 41

Page 42: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

42

14. If we want to use the directive component to be used in many places in the app, then it is better to use the isolated scope. Since the isolated scope can contain the variable similar to the variable in the module, in this case the isolated scope will not affect the module level scopes. So its better to use the Isolated scopes when we are using the directive component in more than one place. We should not create more than one isolated scope in an element

Page 43: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• The ngModel directive binds an input, select, textarea (or custom form control) to a property on the scope.

• Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).• Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine) including

animations.• CSS classes : The following CSS classes are added and removed on the associated input/select/textarea

element depending on the validity of the model. ng-valid is set if the model is valid. ng-invalid is set if the model is invalid. ng-pristine is set if the model is pristine.

ngModel is responsible for

43

style.css.my-input {

background: tranparent;}.my-input.ng-invalid {

color: white;background: red;

}

template.htmlUpdate input to see transitions when valid/invalid.Integer is a valid value.<form name=”testForm” ng-controller = “testcontroller”>

<input ng-model=”formData.value” ng-pattern = “/^\d+$/”

name = “animation” class = “my-input”</form>

controller.jsfunction testcontroller($scope) {

$scope.formData.

value = 1;}

Page 44: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

AngularJs not only supports for the desktop web application, but also supports for

the phones and tablets which has HTML5 compatible browsers.

There are some event handlers which are present for the touch enabled device● $swipe - This supports for the swipe gestures more conveniently● ngClick - In the touch enabled device default ngClick is replaced,since default

ngClick takes 300ms to respond for the click. This version handles the click immediately.

● ngSwipeLeft - Specifies the custom behavior when an element is swiped to the left of the screen

● ngSwipeRight - Specifies the custom behavior when an element is swiped to the right of the screen

Angular for Mobile Application

44

Page 45: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

HTML

Html does not allow nesting of

Form elements.

Angularjs• In AngularJs forms can be nested. This means that the outer

form is valid when all of the child forms are valid as well. • Usage: Angular form can be used as element, as attribute

and as CSS class.Example:

<form name="outerForm">

<div ng-repeat="item in items">

<ng-form name="innerForm">

<input type="text" name="foo" ng-model="item.foo" />

<span ng-show="innerForm.foo.$error.required">required</span>

</ng-form>

</div>

</form>

Nesting Forms in AngularJS

Page 46: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

• KarmaJS is a framework which supports the unit test runner in AngularJs.

• Using NodeJs we can run the preconfigured local web-server of KarmaJs .

• Karma is capable of running the test cases in the remote browsers also.

• For any programming language unit testing is a very vital factor to check the robustness of

the code.

• Unit testing helps you prevent regressions, increase quality, maintainability.

• Since javascript is much more about the dynamic content and executes without the help of

the compiler it has to come with strong test cases. AngularJs has imported many features

which makes the testing easily done.

• KARMA runs on the browsers which are specified in the configuration file.

• While running the unit test cases the DOM is not accessed

• It also provides end to end testing

• We can also add the coverage tool to cover the test cases and reports can be generated for

the test cases.

Unit Test Runner - KarmaJS

46

Page 47: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Controller.js

app.controller(localController, function($scope) { $scope.text = 'Hello World!'; });

Test.js

describe('MainCtrl', function(){ // we'll use this scope in our tests var scope; beforeEach(angular.mock.module('Application'));

beforeEach(angular.mock.inject(function($rootScope, $controller)

{ //Empty scope is created scope = $rootScope.$new(); //Declare the controller and inject our empty

scope $controller('localController', {$scope: scope}); });

//Testing starts here it('should have variable text = "Hello World!"',

function(){ expect(scope.text).toBe('Hello World!); });});

Sample Unit test runner test case using KARMA

Page 48: Angular JS. Contents About Angular JS Hassle free Angular JS MVC pattern of Angular JS Example of MVC pattern Data binding Applying CSS dynamically Templates

Thank You!!!

48

Mail us at: [email protected]