AngularJS_part1

39
AngularJS By Renuka.S Cognizant Interactive Team

description

angulr js

Transcript of AngularJS_part1

AngularJS By Renuka.S

Cognizant

Interactive Team

About Angular • AngularJS an open-source JavaScript framework

maintained by Google

• Runs Single Page Application and provide built-in

support for routing, MVC style programming, services,

factories, modules, testing.

MVC Model-view-controller

JavaScript Data

HTML templates

Application Logic

Modules • AngularJS modules divide your web application into

small, reusable and functional components which can be

integrated with other web applications.

• Each module is identified by a unique name and can be

dependent on other modules.

• Inside your angularjs module you can define following

components:

• Controllers

• Services

• Factories

• Filters

• Directives

Modules (Continous…)

• Creating an AngularJS module

<script type="text/javascript">

angular.module('modulename',[]);

angular.module('modulename',['dependentModule1','dependentMod

ule2'])

</script>

• to include ng-app attribute in HTML

<html ng-app="myApp">

<head>...</head>

<body>...</body>

Controller • Controller is the JavaScript function and it’s a place

where we put our application logic for view.

• Other components (factory, service, filter, directives) can

also be called in the controller

• Each controller has its own scope. Scope is an object

which passes as an argument. This object is used to bind

the controller with view.

• A controller is associated with a HTML element with the

ng-controller directive.

Controller(Continous…)

create controller create controller in an

angular way

function MyCtrl($scope) {

$scope.greeting = “Hello, Angular is

awesome!”;

}

myApplication.controller(‘MyCtrl’,

function($scope) {

$scope.greeting = “Hello, Angular is

awesome!”;

});

$scope

• AngularJS has two scope objects: $rootScope and $scope

• $scope is an object use to communicate between a controller

and a view

• The $rootScope is the top-most scope. An app can have only one

$rootScope which will be shared among all the components of an

app. Hence it acts like a global variable. All other $scopes are

children of the $rootScope.

Controller View

$scope

$scope

Model • A model in angular can be a primitive type such as string,

number, boolean or a complex type such as object.

• Model is just plain javascript object, it lives within controller. module.controller(‘MyCtrl’, function($scope) { // model called ‘greeting’ which is a string $scope.greeting = “Hello, Angular is awesome!”; var users = [ {name: “John Doe”, point: 45 }, {name: “John Nash”, point: 85}, {name: “Johny”, point: 55} ]; // model called ‘user’ which is an array of objects $scope.users = users; });

View • View is what the users see, in angular view is the Document Object

Model (DOM)

• To display the data from controller, you can put angular expression in your view. This expression binds data from model inside your controller

• Since angular is two-way data binding the view will update automatically if there’s a model changes from your controller

<div ng-controller=”MyCtrl”>

<h1>{{greeting}}</h1>

<ol> <li ng-repeat=”user in users”>{{user.name}} - {{user.point}}</li> </ol> </div>

Directives

• Directives are used to make DOM manipulation

• Directives extend the HTML elements with new behaviors

Why directives used in AngularJS

Normal way Angular way

Standard HTML has elements like

<span>, <input>, and <button> that

have fixed behavior

AngularJS makes this easy by

allowing you to wrap all this in a

directive by adding custom

functionality

For example to make the <input>

element behave like a datepicker, it

takes custom CSS and JS calls from

your Javascript code

<input datepicker>

or

<datepicker>

<input id="datepickerElem">

$('#datepickerElem').datepicker()

Directives (continuous..) • AngularJS comes with its own set of built-in directives

and custom directives

• Built-in directives start with the ng- prefix attributes like as ng-app, ng-controller, ng-repeat, ng-model, ng-click etc.

//simple directive example

<div ng-app="app">

<input type="text" ng-model="name">

<div>{{ name }}</div>

</div>

• Name prefix can also be in 5 different way ng-, ng:, ng_, x-ng- ,data-ng-

Directive (continuous…)

• Defining name prefix in different way • <div ng-bind="directivename"></div>

• <div ng:bind="directivename"></div>

• <div ng_bind="directivename"></div>

• <div x-ng-bind="directivename"></div>

• <div data-ng-bind="directivename"></div>

• List of some built-in directives • ng-app="plaintext“

• ng-change="expression“

• ng-checked="boolean“

• ng-disabled="boolean“

• ng-href="plaintext{{string}}“

• ng-mouseover="expression“

• ng-repeat="([key,] value) in object|array“

http://www.cheatography.com/proloser/cheat-sheets/angularjs/

Directive (continuous…)

• Building custom Directives : 4 ways of custom directives used

in the HTML as an element like this

• A new HTML element

<date-picker></date>

• An attribute on an element

<input type="text" date-picker/>

• As a class

<input type="text" class="date-picker"/>

• As comment

<!--directive:date-picker-->

Directive (continuous…) • module.directive(‘arg1’,’arg2’) function registers a new

directive in our module

• The first argument to this function is the directive name

• The second argument is a function which returns a

directive definition object

• While matching directives, Angular strips the prefix x- or

data- from element/attribute names. Then it converts - or :

delimited strings to camelCase and matches with the

registered directives.

• For example in HTML <div my-dir></div> my-dir is an

attribute with ‘–’ and directive name will be myDir

Directive (continuous…) List of properties in the directive definition object

• Restrict

• Template

• TemplateUrl

• Replace

• Priority

• Terminal

• Controller

• Require

• Scope

• Transclude

Directive (continuous…) • Restrict : specify how a directive should be used in HTML.

The restrict option can specify multiple options, as well.

1. E: elements

2. A: attributes

3. C: class names (CSS)

4. M: comments

restrict: ‘A‘ or restrict: ‘EA‘

• Template: This basically replaces the existing contents of an

element.

template: '<div></div>'

• TemplateUrl: A separate html file and reference its location

in templateUrl

templateUrl: 'directive.html'

Directive (continuous…) • Replace: If set to true will replace the element having a

directive on it with a template. If set to false the output

template will be inserted into the element on which the

directive is invoked

replace: true | false

• Priority: sort directives by priority so a directive having

higher priority will be compiled/linked before others.

priority: 1 | 0

• Terminal : If set to true then the current priority will be the

last set of directives which will execute on an element

terminal: true | false

Directive (continuous…) • Controller and Require : Controller function of a directive

is used if you want to allow other directives to

communicate. Require tells Angular to search for the

controller on the element and its parent

require: '^controllerName'

• Scope : By default a directive does not create a new scope

and uses the parent’s scope. Letting all the directives use the

same parent scope might pollute the scope

1. Parent Scope (scope: false)

2. Child Scope (scope:true)

3. Isolated Scope (scope:{})

Directive (continuous…) • Parent Scope: (Scope: false) is a default option which does

not create a new scope for a directive but shares the scope

with its parent. Directive will borrow the controller’s scope

so its parent scope will be $rootScope

• Child Scope : (scope: true) Creates a new scope but

prototypically inherits from the parent scope. the directive

has its own scope so that its parent scope will be the

controller’s scope, not $rootScope

• Isolated Scope: (scope: ‘isolate’) Creates an isolated scope

which does not prototypically inherit from the parent scope

but you can access parent scope using scope.$parent.

Directive (continuous…) • Isolated scope takes an object/hash which lets you derive

properties from the parent scope and bind them to the local scope .There are three ways to do that

1. @ – binds the value of parent scope property (which always a string) to the local scope. So the value you want to pass in should be wrapped in {{}}. Remember `a` in braces.

2. = – binds parent scope property directly which will be evaluated before being passed in.

3. & – binds an expression or method which will be executed in the context of the scope it belongs.

Scope: {

parent: '@',

children: '=',

shout: '&'

}

Directive (continuous…) • Transclude: compile the content of the element and make it

available to the directive

• true - transclude the content of the directive.

transclude: true

• 'element' - transclude the whole element including any

directives defined at lower priority.

transclude: 'element'

Directive (continuous…) Link Function :To utilize the scope, we can make use of a function called link. This is configured by the link property of the definition object. Three arguments in link function

1. scope – The scope passed to the directive. In this case it’s the same as the parent controller scope.

2. elem – The jQLite (a subset of jQuery) wrapped element on which the directive is applied. If you have included jQuery in the HTML before AngularJS is included, this becomes jQuery wrapped instead of jQLite. As the element is already wrapped with jQuery/jQLite, there is no need to again wrap it inside $() for DOM manipulations.

3. attrs – An object representing normalized attributes attached to the element on which the directive is applied.

link: function(scope, elem, attrs) {

elem.bind('click', function() {

//somecode here

});

});

Directive (continuous…) Compile Function : The compile function is used to perform any DOM transformation before the link function runs. It accepts the following arguments.

• element – The element on which the directive is applied.

• attrs – The normalized list of attributes declared on the element

.

compile: function(elem,attrs) {

//do optional DOM transformation here

return function(scope,elem,attrs) {

//linking function here

};

}

};

'

Routing • Routing divide app into multiple view and bind different views

to controllers

• Including the AngularJS Route Module

• <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>

Index.html

ng-view

(placeholder)

About us

view

ContactUs

view

/about us

/contact us

Routing • Declaring a Dependency on the AngularJS Route Module

• var app= angular.module("app", ['ngRoute']);

• Routing uses angularjs service “$routeprovider”

• $routeprovider service provides methods .when() and

.other() to define the routes

• ng-view is the directive that angular uses as a container to

switch between views

<div ng-app=“app">

<ng-view></ng-view> // ng-view directive

</div>

Routing (continuous…)

• ng-view will allow us to set up config function and access the $routeProvider

• Config function with “when” method of the $routeProvider have 2 parameters (route, object {templateUrl property,controller property})

var app = angular.module('app', ['ngRoute']); // create module

// create config fn

app.config(function($routeProvider){

$routeProvider.when('/', // when method

{

templateUrl: 'app.html', // property of obj

controller: 'AppCtrl' // property of obj

}

);

});

Routing (continuous…)

// create the module and name it app also include ngRoute

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

app.config(function($routeProvider) {// configure our routes

$routeProvider.when('/', {

templateUrl : 'pages/home.html',

controller : 'mainController'

})

// route for the about page

.when('/about', {

templateUrl : 'pages/about.html',

controller : 'aboutController'

})

// route for the contact page

.when('/contact', {

templateUrl : 'pages/contact.html',

controller : 'contactController'

})

.otherwise({

redirectTo : '/'

});

});

Routing (continuous…) • Angular throw a hash(#) into the URL.

• For example:

http://example.com/#/about

http://example.com/#/contact

• To get rid of this need to use “$locationProvider “and “html5Mode”

app.config(function($routeProvider, $locationProvider) {

$routeProvider.when('/', {

templateUrl : 'app.html',

controller : 'AppCtrl'

})

});

// use the HTML5 History API

$locationProvider.html5Mode(true);

});

Dependency Injection • Dependency injection is a software design pattern

• AngularJS comes with a built-in dependency injection

mechanism and different components can be accessed by

adding a parameter to the controller function

• Types of components can be injected

• Value

• Factory

• Service

• Provider

• Constant

Values

• A value is a simple object. It can be a number, string or JavaScript object. Values are typically used as configuration which is injected into factories, services or controllers

• Injecting a value into the controller function is done by adding a parameter with the same name as the value

module.value("numberValue", 999); // number value

module.value("stringValue", "abc"); // string value

module.value("objectValue", { val1 : 123, val2 : "abc"} ); // object value

// injecting value in the controller

module.controller("MyController", function($scope, numberValue) { console.log(numberValue);

});

Factory • A factory is an injectable function so AngularJS will call the

function

• Factory creates an object , add properties to it and return the object

• When the factory is injected in the controller, those properties on the object can be accessed in that controller through factory.

module.factory(‘factoryName', function(){

var fac = {}; // creates an object

fac.users = [‘x', y', ‘z'];

return fac;

});

// injecting factory in the controller

module.controller(“controllerName", function($scope, factoryName) { console.log(factoryName);

});

Services • A service is an injectable constructor. A constructor creates a new

object so new is called on a service

• services are singleton objects or functions that carry out specific tasks

• Services are a great way for communicating between controllers like sharing data

module.service(‘serviceName', function() {

// AngularJS will do this internally (var service =new serviceName)

this.method1 = function() {

console.log("done");

}

});

// injecting service in the controller

module.controller(“controllerName", function($scope, serviceName) { serviceName.method1();

});

services • These services can be called from anywhere

Controllers, Directive, Filters.

• Dependencies can be injected in the services

• Internally services

• $http

• $route

• $window

• $location

Provider • A provider is an object with a $get() method. The injector calls

the $get method to create a new instance of a service.

module.provider(‘providerName', function() {

this.$get = function() {

return function(name) {

alert("Hello, " + name);

};

};

});

// injecting service in the controller

module.controller(“controllerName", function($scope, providerName) {

// code here

});

Provider (continuous…) • The Provider can have additional methods which would allow

for configuration of the provider.

• Angular runs your application in two phases the config and run

phases.

• Config phase where directives, controllers, filters get set up

• The run phase angular actually compiles your DOM and starts

up your app

• We can add additional code to be run in these phases with the

module.config and module.run functions. Each take a function

to run during that specific phase

• Values cannot be injected into the module.config()

Constants • A constant can be injected everywhere.

• The value of a constant can never be changed

• In config() function we cannot inject values instead we can

inject constants.

module.constant("configValue", "constant config value");

// injecting Constant in the config

module.config( function(ServiceProvider, configValue ) {

ServiceProvider.doConfig(configValue);

});

Constant

• A provider is an object with a $get() method. The injector calls the $get method to create a new instance of a service. The Provider can have additional methods which would allow for configuration of the provider.

module.provider(‘providerName', function() {

this.$get = function() {

return function(name) {

alert("Hello, " + name);

};

};

});

// injecting service in the controller

module.controller(“controllerName", function($scope, providerName) {

// code here

});

Continue in Part2