24
One weekend with AngularJS Yashobanta Bai

One weekendwith angularjs

Embed Size (px)

DESCRIPTION

This cover all the basic concept of angularJs.

Citation preview

Page 1: One weekendwith angularjs

One weekend with AngularJS

Yashobanta Bai

Page 2: One weekendwith angularjs

One weekend with AngularJs

[email protected] 2

What is AngularJs ? Angular.js, is a open-source client-side(java script) MVC framework used to implement rich Internet application (RIA). AngularJS is based on the MVC pattern (Model View Control). Therefore AngularJS separates your RIA application into models, views and controllers, that makes it easier to implement RIA web applications.It is maintained by Google. AngularJs also provide a really a full-featured SPA (Single Page Application) framework. What is Model , View and Controller ?

The Model is the part of the application that handles the logic for the application data.Often model objects retrieve data (and store data) from a database.

The View is the parts of the application that handles the display of the data.Most often the views are created from the model data.

The Controller is the part of the application that handles user interaction.Typically controllers read data from a view, control user input, and send input data to the model.

In case of angularJs the views are specified using HTML and AngularJS's own template language. The models and controllers are specified via JavaScript objects and JavaScript functions. SPA (Single Page Application) framework : A Single Page Application is one in which we have a shell page and we can load multiple views into that dynamically . So in a traditional application, as you know you typically blink and load everything again that is always it makes a round trip with server. It’s not very efficient on the bandwidth, especially in the mobile world. In a SPA we can load the initial content upfront and then the different views or the little kind of mini- web pages can be loaded on the fly and embedded into the shell. Where AngularJs stands in our application development? Typical traditional application development architecture looks as follows ,

Page 3: One weekendwith angularjs

One weekend with AngularJs

[email protected] 3

AngularJs application development architecture,

If you see above diagram in loosely speaking typical application consist of a UI layer ,a business or application layer and a data layer etc etc.So in which layer the Angular Stands ?Can we write application layer using it ,the answer is big no. Angular only define various ways to organized web application at client side by providing client side MVC pattern .It just enhance the capabilities of client side scripting i.e java script . AngularJs Building Blocks

• Controller Component

• Model Component

• View Component

• Directives

• Filters

• Services

• etc.. Get Started with AngularJs To get started with AngularJS just head over to http://angularjs.org and download agular.min.js file. There are two different options available you can go with the “stable” or the “unstable”. For learning purpose you may use unstable version which contain more updated and newer thing ,but for production environment always use stable version for safer site .

what is a directive? Directives are one of the most powerful feature of AngularJS. Directives in AngularJS are used to make custom HTML elements and simplify DOM manipulation. They allow you to extend HTML to answer the needs of web applications. Angular uses directives to plug its action into the page. AngularJS comes with its own set of built-in directives, as well as the ability to add your own ones. Generally built-in directives are prefaced with ng-, and are placed in html attributes.

Page 4: One weekendwith angularjs

One weekend with AngularJs

[email protected] 4

Some common directives that come inbuilt with Angular are:

• ng-app: this is essentially the initial entry point of Angular to the page. It tells Angular where it gets

to act.

<html ng-app> is all it takes to define a page as an Angular application.

• ng-bind: changes the text of an element to the value of an expression.

<span ng:bind=”name”></span> will display the value of ‘name’ inside the span. Any changes to

‘name’ are reflected instantly in the DOM anywhere the variable is used.

• ng-model: Similar to ng-bind, but allows two-way data binding between the view and the scope.

• ng-controller: specifies the JavaScript class for the given action. Controllers are typically kept in

external .js files.

• ng-repeat: creates the very clean loop structures in your page.

• ng-show & ng-hide : Conditionally show or hide an element, depending on the value of a boolean

expression.

• ng-switch : Conditionally instantiate one template from a set of choices, depending on the value of a

selection expression.

• ng-view : ng-view is the directive that angular uses as a container to switch between views

• ng-if : Basic if statement directive which allow to show the following element if the conditions are

true.

• ng-include : To include a partial .

• ng-class : Used to apply CSS class dynamically.

• ng-disabled : Used to enable or disable a control dynamically.

Bootstrapping AngularJs apps

Bootstrapping AngularJS apps automatically using the ngApp directive is very easy and suitable for most

cases. If you need to have more control over the initialization process, you can use a manual bootstrapping

method instead. For simplicity it is recommended to use ngApp for bootstrapping AngularJs app .

There are 3 important things that happen during the app bootstrap:

1. The injector that will be used for dependency injection is created.

2. The injector will then create the root scope that will become the context for the model of our

application.

3. Angular will then "compile" the DOM starting at the ngApp root element, processing any directives

and bindings found along the way.

AngularJs Hello World Program Example 1: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="Script/angular.min.js"></script> </head> <body ng-app> {{1+2}}

Page 5: One weekendwith angularjs

One weekend with AngularJs

[email protected] 5

</body> </html> Example 2: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="Script/angular.min.js"></script> </head> <body > {{1+2}} <div ng-app > {{1+2}} </div> </body> </html> If you see the out put ,{{1+2}}expression which is present inside the div is get executed according to angularJS so return 3 ,but the first {{1+2}}expression not get evaluated and shows as it is like simple string,because we are using ngApp directive as a attribute of that<div > tag only ,so angularJs processing is only done for that <Div>. Manual Bootstrapping <head> <title></title> <script type="text/javascript" src="Script/angular.min.js"></script> <script> angular.element(document).ready(function () { angular.module('myApp', []); angular.bootstrap(document, ['myApp']); }); </script> </head> <body> {{1+2}} </body> </html> What happens when web page is loaded into the browser

First the HTML document is loaded into the browser, and evaluated by the browser. At this time the AngularJS JavaScript file is loaded, the angular global object is created, and your JavaScript which registers controller functions is executed.

Second, AngularJS scans through the HTML to look for AngularJS apps and views. When AngularJS finds a view it connects that view to the corresponding controller function.

Page 6: One weekendwith angularjs

One weekend with AngularJs

[email protected] 6

Third, AngularJS executes the controller functions and update (render) the views with data from the model populated by the controller. The page is now ready.

Fourth, AngularJS listens for browser events (e.g. input fields being changed, buttons clicked, the mouse moved etc.). If any of these browser events require a view to change, AngularJS will update the view correspondingly. If the event requires that the corresponding controller function is called, AngularJS will do that too. Example 3:

What ng-model does is behind the scenes it’s going to add a property up in the memory called “name” into what’s called “the scope”.

Scope The glue between the View and the Controller is something called the Scope, and in Angular you’re going to see a lot of objects or variables that start with $. $scope represents the scope object. A controller can add data and function in its scope and then they will be accessible in the view.

Using ng-bind The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes. It is similar to {{ }}.

ng-bind vs ng-model ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html. ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>.

Page 7: One weekendwith angularjs

One weekend with AngularJs

[email protected] 7

<head> <title></title> <script src="../angular.min.js"></script> </head> <body ng-app ng-init="name='yash';name1='yash'"> <input type="text" ng-model="name" />{{name}} <input type="text" ng-bind="name1" />{{name1}} </body> </html> On executing ,you can find that both text fields are shows initial name as yash ,then if type something in the first text field then due to ng-model the name get changed but for second text field change not happened due to ng-bind.

Iterating with the ng-repeat Directive

<body> <div ng-init="names=['Sachin','Yash','Varun']"> <ul> <li ng-repeat="name in names">{{name}}</li> </ul> </div> </body>

• We’ve now initialized our data with the ng-init. and iterate through data with the ng-repeat

Filters In order to change the way your data are displayed in your page, AngularJS provides you with the filter mechanism .It provide some predefine filters i.e lowercase ,uppercase , orderBy etc. <body> <div ng-init="names=['Sachin','Yash','Varun']"> <ul> <li ng-repeat="name in names">{{name|uppercase}}</li> </ul> </div> </body>

Client side search using filter

It is not recommended to initialize using ng-init ,in actual the initialization must

goes inside the controller .

Page 8: One weekendwith angularjs

One weekend with AngularJs

[email protected] 8

<body> <div ng init="employees=[{name:'Yalix',city:'Pune'},{name:'Sachin',city:'pune'}, {name:'Yash',city:'Bhubaneswar'},{name:'Varun',city:'Delhi'}]"> <input type="text" ng-model="employeeName" /> <ul> <li ng-repeat="employee in employees|filter:employeeName|orderBy:'city'">{{employee.name|uppercase}}</li> </ul> </div> </body>

Scope going to control ultimately what data gets bound into the View. If the View passes up data to the controller it will handle passing off may be to a service which then updates a back-end data store. Using proper separation of concerns, controllers should never contain anything related to the DOM.

Creating Controller As we already discussed controller is nothing but a simple java script function . So now do the same previous example with the help of controller . <head> <title></title> <script src="../../angular.min.js"></script> <script> function simpleController ($scope) { $scope.employees = [{ name: 'Yalix', city: 'Pune' }, { name: 'Sachin', city: 'pune' }, { name: 'Yash', city: 'Bhubaneswar' }, { name: 'Varun', city: 'Delhi' } ]; };

Page 9: One weekendwith angularjs

One weekend with AngularJs

[email protected] 9

</script> </head> <body ng-app ng-controller="simpleController"> <div> <input type="text" ng-model="employeeName" placeholder="Type Here..." /> <ul> <li ng-repeat="employee in employees|filter:employeeName|orderBy:'city'"> {{employee.name|uppercase}} </li> </ul> </div> </body> </html> Using ng-show / ng-hide directive The ng-show and ng-hide directives are used to show or hide an HTML element depending on condition. These two directives do the same thing, but are each other's opposites. The HTML elements (span elements in this case) are hidden using the CSS property display: none;. That means, that the HTML elements are still present in the DOM. They are just not visible. <head> <title></title> <script src="../../angular.min.js"></script> <script> function simpleController($scope) { $scope.myData = {show:true}; }; </script> </head> <body ng-app > <div ng-controller="simpleController" > <span ng-show="myData.show">Span1</span> <span ng-hide="myData.show">Span2</span> </div> </body> Using ng-if directive The main difference between ng-if and ng-show + ng-hide is that ng-if removes the HTML element completely from the DOM, whereas the ng-show + ng-hide just applies the CSS property display: none; to the elements. <div ng-controller="simpleController" > <span ng-if="myData.show">Span1</span> </div>

Page 10: One weekendwith angularjs

One weekend with AngularJs

[email protected] 10

Using ng-switch directive The ng-switch directive is used if you want to add or remove HTML elements from the DOM based on data in the model. Here is an example: <head> <title></title> <script src="../../angular.min.js"></script> <script> function simpleController($scope) { $scope.myData = {}; $scope.myData.switch = 3; }; </script> </head> <body ng-app > <div ng-switch on="myData.switch"> <div ng-switch-when="1">Shown when switch is 1</div> <div ng-switch-when="2">Shown when switch is 2</div> <div ng-switch-default>Shown when switch is anything else than 1 and 2</div> </div> </body>

• The on attribute tells which data in the model to switch on. Using ng-include directive The ng-include directive can be used to include HTML fragments from other files into the view's HTML template. <div ng-include=" 'test.html' "></div> This example includes the file test.html into the HTML template inside the div having the ng include attribute. The file name should be enclosed in single quotes.

AngularJS Modules Modules are the logical entities that you divide you application in. So your application can contain several modules (like Transaction, Report, etc.). Each module represent a logical entity within the application.

Page 11: One weekendwith angularjs

One weekend with AngularJs

[email protected] 11

Creating a module var myApp = angular.module('myApp', [ ]); The first parameter is indicating the name of the module you want to create and the second is an array that contain the dependency module names.If your module is not dependent upon other then its simple a empty array i.e [ ].

Minification One of the techniques a JavaScript minifier will use to reduce the amount of code sent to the client is to change the names of local variables and parameters to be as small as possible. A parameter named "$http" might come out of a minifier with the name "n" to save at least 4 bytes. Dependency injection in Angular relies on parameter names, a minifier can destroy Angular's ability to inject dependencies. Indeed, once you've minified a file you might see exceptions like , Error: Unknown provider . Before minification controller , function simpleController($scope,$http) { $scope.myData = {}; .... }; After minification controller may looks like , function simpleController(x,n) { .... }; For dependency injection angular did not know what is x and n here ,so shows error like Error: Unknown provider. So to avoid this problem we have to use controller ( ) to create a controller as below example . Best way to create controller var myApp = angular.module('myApp', [ ]); myApp.controller('testController', ['$scope', function ($scope) { $scope.names = ['Sachin', 'Yash', 'Varun']; }]); <body ng-app="myApp" ng-controller="testController"> <ul> <li ng-repeat="name in names">{{name}}</li> </ul> </body> AngularJS Event Listener Directives You attach an event listener to an HTML element using one of the AngularJS event listener directives i.e ng-click ,ng-dblclick , ng-mousedown , ng-mouseup , ng-mouseenter ,ng-mouseleave ,ng-mousemove ,ng-mouseover , ng-keydown ,ng-keyup ,ng-keypress ,ng-change <head> <title></title> <script src="../../angular.min.js"></script> <script> angular.module("myapp", [])

Page 12: One weekendwith angularjs

One weekend with AngularJs

[email protected] 12

.controller("MyController", function ($scope) { $scope.doClick = function ( ) { alert("clicked"); } }); </script> </head> <body ng-app ng-controller="MyController"> <button value="Press" ng-click="doClick( )">Click here</button> </body> Creating Custom Directive As we already discussed angularJs provides built-in directives as well as support for creating your own user define directive to controls the rendering of the HTML inside an AngularJS application. <script> var app= angular.module("myapp", [ ]) app.directive('testDirective', function () { return { restrict: 'E', template: '<div>test</div>' } }); </script> <body ng-app="myapp"> <test-directive> </test-directive> </body> Notice that when we invoke it, the name of the directive is not the same as when we define it (testDirective while consuming should be written as test-directive). This is because AngularJS will handle translating the camel cased name when we define it to the snake case when we invoke it. Parameters used while creating Directives Restrict option: The restrict option is used to specify how a directive can be invoked on the page , there are four different ways to invoke a directive. You can also apply multiple restrict options.But in general we are using either 'A' or 'E' restrict option . 'A' - <span test-directive ></span> 'E' - < test-directive ></ test-directive > 'C' - <span class=" test-directive "></span> 'M' - <!-- directive: test-directive --> Template : This template is an inline template where we are specifying the html that will be appended (or replaced),in general we can said it as the UI of the directive. TemplateUrl : Instead of giving inline html we can also specify a html file name ( templateUrl: template.html' )

Page 13: One weekendwith angularjs

One weekend with AngularJs

[email protected] 13

, which will use ajax to pull the template. Attaching event with directive template var app= angular.module("myapp", [ ]) app.directive('testDirective', function () { return { restrict: 'E', template: '<div><input type="submit" value="Login" ng-click="authenticate( )"/></div>' } }); In this time we put a button inside the directive template and which is attached with a click handler .So now the question is where should we define the handler method i.e authenticate ( ) .So for this lets first see the directive life cycle . Directives compilation and instantiation

When the DOM is done loading and the AngularJS process starts booting up, the first process that happens

is the HTML is parsed by the browser as a DOM tree. This tree is then parsed using AngularJS’s $compile()

method. $compile runs through the DOM tree and looks for directive declarations for the different DOM

elements. Once all directive declarations are found for each DOM element and sorted (by priority), the

directive’s compile function is run and is expected to return a link() function. The $compile() function will

return a linking function that wraps all of the containing DOM element’s directives' linking functions.

Finally, the linking function is invoked with the containing scope that attaches all of the associated

directives to that scope. This is where we’ll do most of the work when building directives, as this is where

we can register listeners, set up watches, and add functionality. The result of this process is why

the live data-binding exists between the scope and the DOM tree. Every directive has its own scope .

Compile ,Link and Controller function • compile function - use for template DOM manipulation (i.e., manipulation of tElement = template

element), hence manipulations that apply to all DOM clones of the template associated with the directive. Note that the compile method only has access to the templates element tElement and template attributes. It has no access to the scope .If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link' attribute is ignored if the 'compile' attribute is defined.

• link function - normally use for registering DOM listeners (i.e., $watch expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned.

• controller function - must be used when another directive needs to interact with this directive ,that is if we want to share some common functionality between directives . This is important to note that we should not do DOM manipulations in our controller function.

Page 14: One weekendwith angularjs

One weekend with AngularJs

[email protected] 14

Why not DOM manipulation in side controller function

when we set controller option for the directive that means we are creating a controller for that directive like

we created previously a controller for a view .This controller is instantiated before the pre-linking phase.The

pre-linking and post-linking phases are executed by the compiler. The pre-link function is executed before

the child elements are linked, while the post-link function is executed after. It is only safe to do DOM

transformations after the post-link function. So we should not do DOM manipulations in our controller

function.

Compile function:

App.directive('compileTest', function() { return { restrict: 'A', compile: function(tElement, tAttrs) { tElement.append('Test compilation phase!'); } }; }); So we can used the directive like <div compile-test></div>

This takes 2 arguments by default:

• tElement – A template element the directive has been declared on.

• tAttrs – A list of attributes associated with the tElement.

In addition, you can inject transcludeFn, directiveController, etc. in it

Link and Controller function var app = angular.module('testModule', []); app.directive('exampleDirective', function() { return { restrict: 'E', template: '<p>Hello {{name}}!</p>', controller: function($scope){ $scope.name = "First "; }, link: function(scope, el, attr) { scope.name = scope.name + "Second "; } } }) we can use the directive like <example-directive></example-directive> A link function by default takes three parameters but we can inject more also:

• scope – A scope to be used by the directive.

• element – An element the directive is bound to.

• attrs – A list of attributes associated with the element.

Page 15: One weekendwith angularjs

One weekend with AngularJs

[email protected] 15

For a controller function by default it takes one parameter that is $scope and as much parameter we want we

can inject .If we see the out put of this directive it shows Hello First Second that means controller get

executed before link . Sharing Scope let see how we can share scope between directive and its parent . <script> var myApp = angular.module('myApp', [ ]); myApp.controller('testController', ['$scope', function ($scope) { $scope.x = 0; }]); myApp.directive('testDirective', function () { return { restrict: 'E', template: 'testDirective x:{{x}}', link: function ($scope) { $scope.y = 0; $scope.x = $scope.x + 1; } } }); </script> </head> <body ng-app="myApp" ng-controller="testController"> TestController X:{{x}} <br /> <test-directive></test-directive> testDirective Y:{{y}} </body> </html> In this example we have created a module 'myApp' which have a controller testController and a directive 'testDirective'. Here we use testDirective inside the body tag and body use testController ,so test controller act as a parent for the testDirective . You have to remember that if you have not define any scope for a directive ,then it by default use its parent scope ,thats the reason here the directive can able to access the parent scope variable x and able to modify that and if you create any variable in that directive then its created that variable inside the parent scope ,that's why here variable 'y' can access inside the body also. scope: false Is the default option which does not create a new scope for a directive but shares the scope with its parent. scope: true Creates a new scope but prototypically inherits from the parent scope. If you execute above example by making scope: true then the variable 'y' is created inside the child scope i.e directive scope and can't be access from parent scope. isolate scope: An isolate scope does not prototypically inherit from the parent scope, but creates an entirely new one. Creating this isolate scope will ensure that your directive does not mess with the existing scope. To create an isolate scope, simply pass an object back in the scope option i.e scope :{}

scope : true

Page 16: One weekendwith angularjs

One weekend with AngularJs

[email protected] 16

Local scope property(@ or @attr) : Binding a local scope (string) to the value of the DOM attribute, use the @ symbol. Now the value of the outer scope will be available inside your directive’s scope,S o the value you want to pass in should be wrapped in {{ }}.

Bi-directional binding(= or =attr): A bi-directional binding can be set up between the local scope property and the parent property using the =symbol. If the parent model changes, just like in normal data-binding then the local property will reflect the change. Parent execution binding (& or &attr) :

To execute a function in the context of the parent scope, we can bind a function using the & symbol. This is

to say that when setting the value, a function wrapper will be created and point to the parent function.

To call the parent method with an argument, you’ll need to pass an object with the key being the name of the

argument and the value being the argument to pass:

Example : <head> <script src="../newLib/angular.min.js"></script> <script> var myApp = angular.module('myApp', []); myApp.controller('testController', ['$scope', function ($scope) { $scope.empName = 'yash'; $scope.empsal = 1000; $scope.save = function () { alert('saved'); }; }]); myApp.directive('testDirective', function () { return { restrict: 'E', scope: { // set up directive's isolated scope name: "@", // name var passed by value (string, one-way) amount: "=", // amount var passed by reference (two-way) callback: "&" // save action }, template: '<input type="submit" ng-click="onSaveclick()" value="Save" />', link: function ($scope) { $scope.name = 'Varun'; $scope.amount = 90000; $scope.onSaveclick = function ( ) { $scope. callback ( ); }; } } }); </script>

Page 17: One weekendwith angularjs

One weekend with AngularJs

[email protected] 17

</head> <body ng-app="myApp" ng-controller="testController"> <test-directive name="{{empName}}" amount="empsal" callback="save()"></test-directive> </body> </html> In this example empName is passed to the directive by using @ ,so what ever changes made to the variable inside the directive scope is not reflected to the parent scope and amount is passed by '=' ,so its a two ways binding and changes made in child scope is reflected to parent also . Then the callback: "&" ,the ampersand "&" indicates this variable holds an expression that is executed in the context of the parent scope. It allows directives to call method ie in this case save actions of parent scope. Service /Factory Angular services/factory are simple singleton object that carry out specific tasks. It basically holds some specific business logic. Angular offers several useful built in services like $http,$q,$timeout for performing various task , you are also free to create your own custom service for your applications.

• The $http service is a core Angular service that facilitates communication with the remote HTTP servers

• For more details regarding inbuilt services have a look on http://docs.angularjs.org/api/ng/service Why custom Service /Factory ? Your controller must be responsible for binding model data to views using $scope . It suppose not to contain any complicated business logic,like It should not contain logic to fetch the data or manipulating it. Then how to achieve it ? For that we must create singleton objects called services/factory. Advantages of using Service /Factory ?

• It fulfills the principle of separation of concern or segregation of duties.

• Each component is responsible for its own work making application more manageable.

• More testable component.

• You can use services to organize and share code across your application. What can be a part of service ? Suppose you create a simple registration page application , the business logic i.e according to your business requirement to whom you want to provide facilities to register and other rule and regulation for registration process or logic to call HTTP url to fetch data from server or store data in server can be put within a service object. Wherever we want to use the service, we just have to specify its name and AngularJS automatically inject these objects by using Dependency Injection design pattern . Service Example var myapp = angular.module('myapp', []); myapp.service('MyService', function() { this.method1 = function() { //..perform your business logic return 'I am in method1'; } });

Page 18: One weekendwith angularjs

One weekend with AngularJs

[email protected] 18

Factory Example var myapp = angular.module('myapp', []); myapp.factory('MyFactory ', function() { var factory = {}; factory.method1 = function() { //..perform your business logic return 'I am in method1'; } return factory; }); Using Service/Factory Example <head> <title></title> <script src="../newLib/angular.min.js"></script> <script> var myapp = angular.module('myapp', [ ] ); myapp.service('MyService', function( ) { this.show = function ( ) { return 'I am in MyService'; } }); myapp.factory('MyFactory', function ( ) { var factory = { }; factory.show = function ( ) { return 'I am in factory'; } return factory; }); myapp.controller('testController', function ($scope, MyService, MyFactory) { $scope.showService = function ( ) { alert(MyService.show( )); }; $scope.showFactory = function ( ) { alert(MyFactory.show( )); }; }); </script> </head> <body ng-app="myapp" ng-controller="testController"> <input type="submit" value="Service Call" ng-click="showService( )" /> <input type="submit" value="Factory Call" ng-click="showFactory( )" /> </body> Asynchronous calls to service in Angular Synchronous means that you call a web service (or function ) and wait until it returns - all other code execution and user interaction is stopped until the call returns. Asynchronous means that you do not halt all

Page 19: One weekendwith angularjs

One weekend with AngularJs

[email protected] 19

other operations while waiting for the web service call to return. Other code executes and/or the user can continue to interact with the page (or program UI). AngularJS offers promises via a service called $q which is used to dealing with the asynchronous nature of some things you’ll do within JavaScript. For example, calling remote services. We are using http://echo.jsontest.com/key/value/one/two ,which is a sample REST service that's returns a customized JSON object as following JSON:

{ "one": "two",

"key": "value"

}

<head> <script src="../newLib/angular.min.js"></script> <script> var myapp = angular.module('myapp', [ ]); myapp.service('MyService', function ($q, $http) { this.asynCall = function ( ) { var defer = $q.defer( ); $http.get('http://echo.jsontest.com/key/value/one/two'). then(function (result) { defer.resolve(result.data); }, function (error) { console.log(error); }) return defer.promise; }; }); myapp.controller('testController', function ($scope, MyService) { $scope.asynServiceCall = function ( ) { MyService.asynCall( ).then(function (result) { console.log(result); }, function (error) { console.log(error); }); }; }); </script> </head> <body ng-app="myapp" ng-controller="testController"> <input type="submit" value="Asyn Service Call" ng-click="asynServiceCall( )" /> </body> AngularJS Routing And Views As we already discussed Angular provide a SPA framework .A Single Page Application(SPA) is one in which we have a shell page and we can load multiple views into that dynamically. Angular use Routing to

Page 20: One weekendwith angularjs

One weekend with AngularJs

[email protected] 20

load different views dynamically and is supported by $routeProvider. Routing helps you in dividing your application in logical views and bind different views to Controllers. For an example there may be a shopping site which have multiple logical view for an example one may be the view which shows all the shopping items ,another may be a view that shows your shopping cart details and another may shows the check out information and that is checkout view. In above diagram we create three Route url /showItems , / shopingCart and / checkout. Each points to a specific view and is managed by a controller.We have to use config()method to configure $routeProvider. $routeProvider provides method .when() and .otherwise() which we can use to define the routing for our application. Routing Example Let see a simple application which have two menus Home and contact Us ,if user click on the home link it should display home.html page and if on contact us then it should shows contact us page. By default it should display home.html .

MySite/#showItems

MySite/#shopingCart

MySite/#checkout

Views controller

Show shopping items shoppingItemController

Show shopping cart

check out process

cartController

checkoutController

• Create a template folder that contain all your partial views and a master page or shell page or parent page here it is index.html which going to use those child views .

Page 21: One weekendwith angularjs

One weekend with AngularJs

[email protected] 21

Index.html <head> <title>AngularJS Routing example</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script src="app.js"></script> <style> ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; } li { float: left; } a:link, a:visited { display: block; width: 120px; font-weight: bold; color: #FFFFFF; background-color: #98bf21; text-align: center; padding: 4px; text-decoration: none; text-transform: uppercase; } a:hover, a:active { background-color: #7A991A; } </style> </head> <body ng-app="sampleApp"> <ul> <li><a href="#home">Home</a></li> <li><a href="#contactUs">Contact Us</a></li> </ul> <div ng-view></div> </body> app.js //Define an angular module for our app ar sampleApp = angular.module('sampleApp', [ ]); //Define Routing for app sampleApp.config(['$routeProvider',

Page 22: One weekendwith angularjs

One weekend with AngularJs

[email protected] 22

function($routeProvider) { $routeProvider. when('/home', { templateUrl: 'templates/home.html', controller: 'homeController' }). when('/contactUs', { templateUrl: 'templates/contactUs.html', controller: 'contactUsController' }). otherwise({ redirectTo: '/home' }); }]); //controller for home view sampleApp.controller('homeController', function ($scope) { $scope.message = 'This is Home page..'; }); //controller for contact us view sampleApp.controller('contactUsController', function ($scope) { $scope.message = 'This is contactUs page..'; }); Just put {{ message }} inside the home.html and contactUs.html. How to pass Parameters in Route Urls? We saw how to define route in above example. Now let us see how to pass parameters in route urls. Consider a scenario where we want to display details of different shopping item based on a parameter i.e item_no or name. So we need to create a view that accept a parameter that is item_no and depending up on that it load the information.

Adding parameter in routing like below, when('/ShowItem/:itemNo', { templateUrl: 'templates/showItem.html', controller: 'ShowItemController' }); And we can read the parameter in 'ShowItemController by using $routeParams.itemNo , in the show item view you can use <a href="#ShowItem/1">show tem1</a>.

Page 23: One weekendwith angularjs

One weekend with AngularJs

[email protected] 23

Call routing dynamically on Click Now consider the same previous example ,but this time we want to have a home button in the contact us page so as soon as user click that button ,it takes to the home page ,that means we want routing dynamically at run time by using $ location. contactUs.html {{ message }} <button ng-click="go('/home')">Home</button> contactUsController sampleApp.controller('contactUsController', function ($scope, $location) { $scope.message = 'This is contactUs page..'; $scope.go = function (path) { $location.path(path); }; });

Points to remember In all of our example ,we put controller ,directive ,service etc code in a single file ,only for the sake of simplicity ,but in real application you must kept then in different file ,for an example your view file let say login.html ,controller looks like loginController,JS ,service looks like UserAuthenticateService.JS. You should link them using script tag in your main file. Angular application folder structure Ultimately how you organize your code is entirely up to you and your team.So it varies from project to project or person to person . So a simple project structure looks like below ,

• So for me, all of my code goes in the app folder, 3rd party or vendor scripts go in the scripts folder, assets in the content folder, and tests in the test folder.

Page 24: One weekendwith angularjs

One weekend with AngularJs

[email protected] 24

Conclusion

Use this material only as a reference or as a starter kit for your learning and then do explore more and more your self ,and feel free to provide your suggestions or bugs/errors that you encounter while using this.

• In side the app folder again their exist some subfolder and itself describe what is going to contain.

• The root of the folder is where I put my app.js which is my boot file. This is from where all the application gets kicked off. For angular this means the modules get loaded and run.

• create a config.js here to store all of commonly used variables across the app.