Top Banner
AngularJS By Renuka.S Cognizant Interactive Team
39

AngularJS_part1

Dec 11, 2015

Download

Documents

premaavk

angulr js
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: AngularJS_part1

AngularJS By Renuka.S

Cognizant

Interactive Team

Page 2: AngularJS_part1

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.

Page 3: AngularJS_part1

MVC Model-view-controller

JavaScript Data

HTML templates

Application Logic

Page 4: AngularJS_part1

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

Page 5: AngularJS_part1

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>

Page 6: AngularJS_part1

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.

Page 7: AngularJS_part1

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!”;

});

Page 8: AngularJS_part1

$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

Page 9: AngularJS_part1

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; });

Page 10: AngularJS_part1

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>

Page 11: AngularJS_part1

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()

Page 12: AngularJS_part1

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-

Page 13: AngularJS_part1

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/

Page 14: AngularJS_part1

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-->

Page 15: AngularJS_part1

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

Page 16: AngularJS_part1

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

• Restrict

• Template

• TemplateUrl

• Replace

• Priority

• Terminal

• Controller

• Require

• Scope

• Transclude

Page 17: AngularJS_part1

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'

Page 18: AngularJS_part1

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

Page 19: AngularJS_part1

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:{})

Page 20: AngularJS_part1

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.

Page 21: AngularJS_part1

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: '&'

}

Page 22: AngularJS_part1

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'

Page 23: AngularJS_part1

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

});

});

Page 24: AngularJS_part1

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

};

}

};

'

Page 25: AngularJS_part1

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

Page 26: AngularJS_part1

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>

Page 27: AngularJS_part1

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

}

);

});

Page 28: AngularJS_part1

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 : '/'

});

});

Page 29: AngularJS_part1

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);

});

Page 30: AngularJS_part1

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

Page 31: AngularJS_part1

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);

});

Page 32: AngularJS_part1

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);

});

Page 33: AngularJS_part1

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();

});

Page 34: AngularJS_part1

services • These services can be called from anywhere

Controllers, Directive, Filters.

• Dependencies can be injected in the services

• Internally services

• $http

• $route

• $window

• $location

Page 35: AngularJS_part1

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

});

Page 36: AngularJS_part1

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()

Page 37: AngularJS_part1

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);

});

Page 38: AngularJS_part1

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

});

Page 39: AngularJS_part1

Continue in Part2