Вы находитесь на странице: 1из 45

Agenda

Why AngularJS ?
Introduction to Single-Page-Apps and MVVM framework
Two way binding

Templates
Controllers
Scopes
Directives
Using and writing filters

Why AngularJS ?
MVC architecture
Two day data binding
Very less DOM manipulation and handling
Custom directives
Templates

Dependency Injection

Single-Page-Apps
No page reload
URL paths route pre-fetched/dynamic resources
Page state, history and navigation are maintained
Each page is a view and has its own controller and scope
ng-route and ui-router

MVC or MVVM

MVC or MVVM

Expressions
Angular expressions are JavaScript-like code snippets
that are usually placed in bindings such
as {{ expression }}.
1+2
a+b
user.name
items[index]

Expressions Angular vs
JavaScript
Context: JavaScript expressions are evaluated against the global window. In
Angular, expressions are evaluated against a scope object.
Forgiving: In JavaScript, trying to evaluate undefined properties generates
ReferenceError or TypeError. In Angular, expression evaluation is forgiving to
undefined and null.
No Control Flow Statements: you cannot use the following in an Angular
expression: conditionals, loops, or exceptions.
Filters: You can use filters within expressions to format data before displaying
it.

Two-Way Data Binding


Automatic synchronization of data between model and
view

Controllers do not need to directly manipulate the view


Changes in the models / data are automatically reflected in
the view

Updates are managed by the frameworks

Two-Way Data Binding

$compile
o Compiler is an Angular service which traverses the
DOM looking for attributes. The compilation process
happens in two phases.
o The compile phase where all of the directives are
identified and sorted by priority.
o Linking phase where any work which "links" a
specific instance of the scope and the specific
instance of an DOM element is performed.

$apply, $digest and $watch


AngularJS directives setup listeners to the view objects
wrapped by $apply function call.
$apply in turn triggers the $digest loop using
$scope.$digest()
$digest in turns triggers all the $watch() in the $watch list
$watch will evaluate each model objects old value with
new value and if change is found, then the view is
updated

Trigger $apply manually


Delayed Message: {{message}}
setTimeout(function() {
$scope.$apply(function() {
$scope.message = 'Fetched after 3 seconds';
});
}, 2000);

Templates
Written with HTML that contains Angular-specific
elements and attributes.
Combines the template with information from the
model and controller to render the dynamic view
Display multiple views within one main page using
"partials" segments of template located in separate
HTML files.

Templates - Elements
Directive An attribute or element that augments an
existing DOM element or represents a reusable DOM
component.
Markup The double curly brace notation {{ }} to bind
expressions to elements is built-in Angular markup.
Filter Formats data for display.
Form controls Validates user input.

Templates - Example
<html ng-app>
<body ng-controller="MyController">

<input ng-model="foo" value="bar>


<button ngclick="changeFoo()">{{buttonText}}</button>

</body></html>

Controllers
Contains only the business logic needed for a single
view.
Controller is a JavaScript constructor function that is
used to augment the Angular Scope.
Set up the initial state of the $scope object.
Add behavior to the $scope object.

Controllers
var myApp = angular.module('myApp',[]);
myApp.controller('DoubleController', ['$scope', function($scope) {
$scope.greeting = Hello World!';

$scope.double = function(value) { return value * 2; };


}]);
<div ng-controller="DoubleController"> {{greeting}}
Two times <input ng-model="num"> equals {{ double(num) }}
</div>

$Scope
o Scope is an object that refers to the application model.
o It is the glue between controller and the view.
o It is an execution context for expressions.
o Scopes are arranged in hierarchical structure which mimic
the DOM structure of the application.
o Scopes can watch expressions and propagate events.

$Scope - APIs
o Scopes provide APIs ($watch) to observe model
mutations.
o Scopes provide APIs ($apply) to propagate any
model changes through the system into the view
from outside of the "Angular realm" (controllers,
services, Angular event handlers).

$Scope - Hierarchies
o One root scope and several child scopes.
o Directives create new child scopes.
o New scopes are added as children of their parent scope.
o When Angular evaluates {{name}}, it first looks at the
scope associated with the given element for the name
property. If no such property is found, it searches the
parent scope and so on until the root scope is reached.

$Scope Hierarchies

$Scope Retrieve in DOM


Right click on the element of interest in your browser and
select 'inspect element'. You should see the browser
debugger with the element you clicked on highlighted.
The debugger allows you to access the currently selected
element in the console as $0 variable.
To retrieve the associated scope in console execute:
angular.element($0).scope() or just type $scope

$Scope manipulation
angular.element(myDomElement).scope();
angular.element(myDomElement).scope().myVar = 5;

angular.element(myDomElement).scope().myArray.push(
newItem);
angular.element(myDomElement).scope().$apply();

Directives
Markers on a DOM element (such as an attribute,
element name, comment or CSS class)
It tells AngularJS's HTML compiler ($compile) to attach a
specified behavior to that DOM element or even transform
the DOM element and its children.
Built-in directives , like ngBind, ngModel, and ngClass, so
on
Developers can create their own custom directives as well

Directives Many forms


<span ng-bind="name"></span>

<my-dir></my-dir>

<span ng:bind="name"></span>

<span my-dir="exp"></span>

<span ng_bind="name"></span>

<!-- directive: my-dir exp -->

<span data-ng-bind="name>

<span class="my-dir: exp;"></span>

<span x-ng-bind="name"></span>

ngBind Directive
The ngBind directive is generally applied to a span
element and replaces the content of the element with the
results of the provided expression.
It has the same meaning as that of the double curly
markup, for example, {{expression}}.
This is to hide the double curly braces from being shown,
when the angular is still compiling.

Example -> <h3 ng-bind="appTitle"></h3>

ngRepeat Directive
The ngRepeat directive is really useful to iterate over arrays
and objects.
Iterates rows of a table, the elements of a list, and even the
options of select.
Syntax - variable in array
<tr ng-repeat="car in cars">
<td><span ng-bind="car.plate"></span></td>
<td><span ng-bind="car.entrance"></span></td> </tr>

ngRepeat injected
variables

ngModel
The ngModel directive attaches the element to a
property in the scope, thus binding the view to the
model.
The element can be input (all types), select,
or textarea
<input type="text" ng-model="car.plate"
placeholder="What's the plate?" />

Misc directives
Built-in directive

Purpose

ngStyle

Supplies the dynamic style configuration demand.


<span ng-bind="car.color" ng-style="{color: car.color}"> </span>

ngShow / ngHide

Display or hides the element based on condition


<div ng-hide="cars.length > 0">

ngClass

Allows you to dynamically set CSS classes on an HTML element

ngApp

Auto-bootstrap an AngularJS application. The ngApp directive designates


the root element of the application and is typically placed near the root
element of the page - e.g. on the <body> or <html> tags.

ngInclude

Fetches, compiles and includes an external HTML fragment.

ngSrc

Using Angular markup like {{hash}} in a src attribute doesn't work right.
Instead use ngSrc.

Custom Directives
Properties

Purpose

Restrict

'A' - <span ng-sparkline></span>


'E' - <ng-sparkline></ng-sparkline>
'C' - <span class="ng-sparkline"></span>
'M' - <!-- directive: ng-sparkline -->

Template

Inline HTML

TemplateUrl

To load a template over ajax, you can specify the templateUrl option, which will use
ajax to pull the template.

compile()

Both manipulates the DOM before its rendered and return a link function (that will
handle the linking for us). Methods shared with all of the instances of this directive.

link()

Register all listeners on a specific DOM element (thats cloned from the template)
and set up our bindings to the page.

Require

To enforce a dependency that a controller of the given name should be present

Template-expanding
directive
angular.module('docsSimpleDirective', [])
.directive('myCustomer', function() {
return {

template: 'Name: {{customer.name}} Address:


{{customer.address}}'
};
});

<div ng-controller="Controller">
<div my-customer></div>
</div>

Template-expanding
directive
angular.module('docsSimpleDirective', [])
.directive('myCustomer', function() {
return {

templateUrl: 'my-customer.html' };
});

<div ng-controller="Controller">
<div my-customer></div>
</div>

my-customer.html
Name: {{customer.name}} Address:
{{customer.address}}

Isolating the Scope of a


Directive
angular.module(abc', [])

restrict: 'E',

.controller('Controller', ['$scope',
function($scope) {

scope: {
customerInfo: '=info'

$scope.naomi = { name: 'Naomi', address:


'1600 Amphitheatre' };

},

$scope.igor = { name: 'Igor', address: '123


Somewhere' };

templateUrl: 'my-customer-iso.html'
};

}])
});
.directive('myCustomer', function() {
return {

Isolating the Scope of a


Directive
<div ng-controller="Controller">
<my-customer info="naomi"></my-customer>
<hr>

<my-customer info="igor"></my-customer>
</div>

Name: {{customerInfo.name}} Address:


{{customerInfo.address}}

Directive that Manipulates


the DOM
myapp.directive('userinfo', function() {

element.css("background-color",
"#ffff00");

var directive = {};


}
directive.compile = function(element, attributes)
{

return linkFunction;

element.css("border", "1px solid #cccccc");

var linkFunction = function($scope, element,


attributes) {

return directive;
})

element.html("This is the new content: " +


$scope.firstName);

Transclusion
myapp.directive('mytransclude', function() {
var directive = {};
directive.transclude = true;

directive.template = "<div class='myTransclude' ng-transclude></div>;


return directive;
});

Ex - <mytransclude>This is a transcluded directive {{firstName}}</mytransclude>

Filters
A filter formats the value of an expression for display to the
user.
They can be used in view templates, controllers or services and
it is easy to define your own filter.
Syntax:
{{ expression | filter }}
{{ expression | filter1 | filter2 | ... }}
{{ expression | filter:argument1:argument2:... }}

Example: {{ 1234 | number:2 }}

Built-in filters

Invoke filter from Controllers,


services, etc
controller('FilterController', ['filterFilter', function(filterFilter) {
this.array =

[ {name: 'Tobias'}, {name: 'Jeff'}, {name: 'Brian'}, {name: 'Igor'}, {name:


'James'}, {name: 'Brad'} ];

this.filteredArray = filterFilter(this.array, 'a');


}

Custom Filters
Register a new filter factory function with your module.
Internally, this uses the filterProvider.
This factory function should return a new filter function
which takes the input value as the first argument.
Any filter arguments are passed in as additional
arguments to the filter function.

Custom Filters - Example


<div ng-controller="MyController">
<input ng-model="greeting" type="text"><br>\

Base64 encoded: {{greeting|ncode:true}}<br>


</div>

Custom Filters - Example


angular.module(abc', [])
.filter(ncode', function() {
return function(input, ncode) {
if(ncode){ return btoa(input); }
else { return atob(input); }

}; });

Вам также может понравиться