SlideShare ist ein Scribd-Unternehmen logo
1 von 27
AngularJS 
Jason
Agenda 
• What is AngularJS 
• AngularJS Features 
• Directives、Filters and Data Binding 
• Views、Controllers and Scope 
• Modules and Factories
SPA 
• Single Page Application 
• In which we have a shell page and we can load multiple views into that. 
• The Challenge with SPAs 
• DOM Manipulation、Caching、Data Binding…etc.
AngularJS 
• AngularJS is one core library. 
• AngularJS is a structural framework for dynamic web apps 
• AngularJS is a full-featured SPA framework
AngularJS
AngularJs 
• Angular takes another approach. 
• Data binding, as in {{}}. 
• DOM control structures for repeating/hiding DOM fragments. 
• Support for forms and form validation. 
• Attaching code-behind to DOM elements. 
• Grouping of HTML into reusable components.
Directives 
• A directive is really a way to teach HTML new tricks. 
• At a high level, directives are markers on a DOM element (such as an attribute, 
element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) 
to attach a specified behavior to that DOM element or even transform the DOM 
element and its children.
Using Directives and DataBinding Syntax 
<!DOCTYPE html> 
<html ng-app> 
<head> 
<script src="angular.min.js"></script> 
<title></title> 
</head> 
<body> 
Name:<input type=“text” ng-model=“name” /> {{ name}} 
<p ng-bind="name"></p> 
</body> 
</html> 
Directive 
Directive 
Data Binding Expression 
Directive
Matching Directives 
• Any time you see ng- that is an Angular directive 
• The normalization process is as follows: 
• Strip 「x-」and 「data-」from the front of the element/attributes. 
• Convert the「:」,「-」, or「_」delimited name to camelCase. 
• Example 
• <input type="text" ng-model="name" /> 
• <input type="text" data-ng-model="name" /> 
• <input type="text" ng:model="name" /> 
• <input type="text" ng_model="name" />
Directives 
• ng-app directive 
• Use this directive to auto-bootstrap an AngularJS application. 
• ng-bind directive 
• 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. 
• ng-model directive 
• The ngModel directive binds an input,select, textarea (or custom form control) to a 
property on the scope using NgModelController, which is created and exposed by this 
directive.
Angular Expressions 
• Angular expressions are JavaScript-like code snippets that are usually 
placed in bindings such as {{ expression }}. 
• For example, these are valid expressions in Angular: 
• 1+2 
• a+b 
• user.name 
• Items[index]
Lterating with the ng-repeat Directive 
<div data-ng-init="names=['John Smith', 'John Doe', 'Jane Doe']"> 
<ul> 
<li data-ng-repeat="name in names"> 
{{name}} 
</li> 
</ul> 
</div>
Using Filters 
<input type="text" data-ng-model="nameText" /> 
<div data-ng-init="names=['John Smith', '1John Doe', 'Jane Doe']"> 
<ul> 
<li data-ng-repeat="name in names | filter:nameText"> 
{{name | uppercase}} 
</li> 
</ul> 
</div>
Understanding Angular Filters 
{{ 99 * 99 | number}} 
{{ 9999 + 1 | number:2 }} 
{{ 99 * 99 | currency}} 
{{ 99 * 99 | currency: 'NT$'}} 
{{'Hello World' | uppercase}} 
{{'Hello World' | lowercase}} 
{{ 1393300831 | date: 'medium'}} 
{{ 1393300831 | date: 'yyyy-MM-dd'}} 
{{ obj | json}}
Understanding Angular Filters 
• Format Conver Data Filter 
• currency custom filter 
• number limiTo 
• date orderBy 
• lowercase 
• uppercase 
• json
View, Controllers and Scope 
View $scope Controller 
$scope is the "glue"(ViewModel) between a controller and a view
Understanding Controllers 
• In Angular, a Controller is a JavaScript constructor function that is used to 
augment the Angular Scope 
• When a Controller is attached to the DOM via the ng-controller directive, Angular 
will instantiate a new Controller object, using the specified Controller's constructor 
function. 
• A new child scope will be available as an injectable parameter to the Controller's 
constructor function as $scope.
Creating a View and Controller 
<div class="container" data-ng-controller="SimpleController"> 
<h3>Adding a Simple Controller</h3> 
<input type="text" data-ng-model="name" /> 
<ul> 
<li data-ng-repeat="cust in customers"> 
{{ cust.name }} - {{ cust.city}} 
</li> 
</ul> 
</div> 
Access $scope 
<script> 
Basic controller 
function SimpleController($scope) 
{ 
$scope.customers = [ 
{name : 'Dave Jones', city:'Phoenix'}, 
{name : 'Jamie Riley', city:'Atlanta'}, 
{name : 'Heedy Wahlin', city:'Chandler'}, 
{name : 'Thomas Winter', city:'Seattle'}, 
]; 
} 
</script> 
So now we have two properties in the scope. The ng-model is going to add a property in the scope 
called name, and we can actually get to that now in the controller by saying $scope.name
Create a Controller in a Module 
Module that demoApp 
depends on 
var demoApp = angular.module('demoApp', []); 
demoApp.controller('SimpleController', function($scope) { 
$scope.customers = [ 
{name : 'Dave Jones', city:'Phoenix'}, 
{name : 'Jamie Riley', city:'Atlanta'}, 
{name : 'Heedy Wahlin', city:'Chandler'}, 
{name : 'Thomas Winter', city:'Seattle'} 
]; 
});
Create a Controller in a Module 
var demoApp = angular.module('demoApp', []); 
demoApp.controller('SimpleController', ['$scope', function(scope){ 
scope.customers = [ 
{name : 'Dave Jones', city:'Phoenix'}, 
{name : 'Jamie Riley', city:'Atlanta'}, 
{name : 'Heedy Wahlin', city:'Chandler'}, 
{name : 'Thomas Winter', city:'Seattle'} 
]; 
}]);
Create Multi Controller in a Module 
var demoApp = angular.module('demoApp', []); 
var controllers = {}; 
controllers.SimpleController = function($scope) { 
…… 
}; 
controllers.SimpleController2 = function($scope) { 
…… 
}; 
demoApp.controller(controllers);
The Role of Factories 
var demoApp = angular.module('demoApp', []) 
.factory('simpleFactory', function(){ 
var factory = {}; 
var customers = [………]; 
factory.getCustomers = function(){ 
return customers; 
}; 
return factory; 
}).controller('SimpleController', function($scope, simpleFactory) 
{ 
$scope.customers = simpleFactory.getCustomers(); 
}); 
Factory injected into 
controller at runtime
Create Custom Directive 
angular.module('docsSimpleDirective', []).controller('Controller', function($scope) { 
$scope.customer = { 
name: 'Naomi', 
address: '1600 Amphitheatre' 
}; 
}).directive('myCustomer', function() { 
return { 
restrict: 'A', 
template: 'Name: {{customer.name}} Address: {{customer.address}}' 
}; 
}); 
<div ng-controller="Controller"> 
<div my-customer></div> 
</div>
$inject 
• If a function has an $inject property and its value is an array of strings, then 
the strings represent names of services to be injected into the function. 
var MyController = function(renamed$scope, renamedGreeter) { 
... 
} 
MyController['$inject'] = ['$scope', 'greeter'];
Value VS. Service VS. Factory VS. Provider 
• Value 
• module.value('valueName', valueObj); 
• Get value from valueObj 
• Service 
• module.service( 'serviceName', ServiceFunction ); 
• Get service from 'new ServiceFunction()'. 
• Factory 
• module.factory( 'factoryName', FactoryFunction ); 
• Get factory from the value that is returned by invoking the FactoryFunction. 
• Provider 
• module.provider( 'providerName', ProviderFunction); 
• Get provider fromnew ProviderFunction().$get()
$watch 
• $watch(watchExpression, listener, [objectEquality]) 
• Registers a listener callback to be executed whenever the watchExpression changes 
• $watchCollection(watchExpression, listener) 
• Shallow watches the properties of an object and fires whenever any of the properties 
change
Reference 
• AngularJS In 60 Minutes 
• http://fastandfluid.com/publicdownloads/AngularJSIn60MinutesIsh_DanWahlin_May2 
013.pdf 
• AngularJS 
• https://angularjs.org/

Weitere ähnliche Inhalte

Was ist angesagt?

CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)
brian d foy
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 

Was ist angesagt? (20)

Angular js - 4developers 12 kwietnia 2013
Angular js - 4developers 12 kwietnia 2013Angular js - 4developers 12 kwietnia 2013
Angular js - 4developers 12 kwietnia 2013
 
Dartprogramming
DartprogrammingDartprogramming
Dartprogramming
 
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
SenchaCon 2016: Handle Real-World Data with Confidence - Fredric Berling
 
How to Mess Up Your Angular UI Components
How to Mess Up Your Angular UI ComponentsHow to Mess Up Your Angular UI Components
How to Mess Up Your Angular UI Components
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Web 5 | JavaScript Events
Web 5 | JavaScript EventsWeb 5 | JavaScript Events
Web 5 | JavaScript Events
 
Symfony World - Symfony components and design patterns
Symfony World - Symfony components and design patternsSymfony World - Symfony components and design patterns
Symfony World - Symfony components and design patterns
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Web 2 | CSS - Cascading Style Sheets
Web 2 | CSS - Cascading Style SheetsWeb 2 | CSS - Cascading Style Sheets
Web 2 | CSS - Cascading Style Sheets
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Handlebars
HandlebarsHandlebars
Handlebars
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 

Andere mochten auch (8)

Moq 的進階用法
Moq 的進階用法Moq 的進階用法
Moq 的進階用法
 
20131209 ms build_using_task By Anney
20131209 ms build_using_task By Anney20131209 ms build_using_task By Anney
20131209 ms build_using_task By Anney
 
Ian 2014.10.24 weekly report
Ian 2014.10.24 weekly reportIan 2014.10.24 weekly report
Ian 2014.10.24 weekly report
 
Introducción tic
Introducción ticIntroducción tic
Introducción tic
 
Ms build – inline task
Ms build – inline taskMs build – inline task
Ms build – inline task
 
Custom action filterattribute
Custom action filterattributeCustom action filterattribute
Custom action filterattribute
 
Knockout validation 心得分享
Knockout validation 心得分享Knockout validation 心得分享
Knockout validation 心得分享
 
How totestinternalprotectmethodsinc#
How totestinternalprotectmethodsinc#How totestinternalprotectmethodsinc#
How totestinternalprotectmethodsinc#
 

Ähnlich wie AngularJS

Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 

Ähnlich wie AngularJS (20)

Angular
AngularAngular
Angular
 
Angular
AngularAngular
Angular
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
 
Angular js
Angular jsAngular js
Angular js
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
 
Valentine with AngularJS
Valentine with AngularJSValentine with AngularJS
Valentine with AngularJS
 
Angular js
Angular jsAngular js
Angular js
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
AngularJS in 60ish Minutes - Dan Wahlin | FalafelCON 2014
AngularJS in 60ish Minutes - Dan Wahlin | FalafelCON 2014AngularJS in 60ish Minutes - Dan Wahlin | FalafelCON 2014
AngularJS in 60ish Minutes - Dan Wahlin | FalafelCON 2014
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
Angular presentation
Angular presentationAngular presentation
Angular presentation
 
Angular.js is super cool
Angular.js is super coolAngular.js is super cool
Angular.js is super cool
 
Built in filters
Built in filtersBuilt in filters
Built in filters
 

Mehr von LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

AngularJS

  • 2. Agenda • What is AngularJS • AngularJS Features • Directives、Filters and Data Binding • Views、Controllers and Scope • Modules and Factories
  • 3. SPA • Single Page Application • In which we have a shell page and we can load multiple views into that. • The Challenge with SPAs • DOM Manipulation、Caching、Data Binding…etc.
  • 4. AngularJS • AngularJS is one core library. • AngularJS is a structural framework for dynamic web apps • AngularJS is a full-featured SPA framework
  • 6. AngularJs • Angular takes another approach. • Data binding, as in {{}}. • DOM control structures for repeating/hiding DOM fragments. • Support for forms and form validation. • Attaching code-behind to DOM elements. • Grouping of HTML into reusable components.
  • 7. Directives • A directive is really a way to teach HTML new tricks. • At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.
  • 8. Using Directives and DataBinding Syntax <!DOCTYPE html> <html ng-app> <head> <script src="angular.min.js"></script> <title></title> </head> <body> Name:<input type=“text” ng-model=“name” /> {{ name}} <p ng-bind="name"></p> </body> </html> Directive Directive Data Binding Expression Directive
  • 9. Matching Directives • Any time you see ng- that is an Angular directive • The normalization process is as follows: • Strip 「x-」and 「data-」from the front of the element/attributes. • Convert the「:」,「-」, or「_」delimited name to camelCase. • Example • <input type="text" ng-model="name" /> • <input type="text" data-ng-model="name" /> • <input type="text" ng:model="name" /> • <input type="text" ng_model="name" />
  • 10. Directives • ng-app directive • Use this directive to auto-bootstrap an AngularJS application. • ng-bind directive • 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. • ng-model directive • The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
  • 11. Angular Expressions • Angular expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. • For example, these are valid expressions in Angular: • 1+2 • a+b • user.name • Items[index]
  • 12. Lterating with the ng-repeat Directive <div data-ng-init="names=['John Smith', 'John Doe', 'Jane Doe']"> <ul> <li data-ng-repeat="name in names"> {{name}} </li> </ul> </div>
  • 13. Using Filters <input type="text" data-ng-model="nameText" /> <div data-ng-init="names=['John Smith', '1John Doe', 'Jane Doe']"> <ul> <li data-ng-repeat="name in names | filter:nameText"> {{name | uppercase}} </li> </ul> </div>
  • 14. Understanding Angular Filters {{ 99 * 99 | number}} {{ 9999 + 1 | number:2 }} {{ 99 * 99 | currency}} {{ 99 * 99 | currency: 'NT$'}} {{'Hello World' | uppercase}} {{'Hello World' | lowercase}} {{ 1393300831 | date: 'medium'}} {{ 1393300831 | date: 'yyyy-MM-dd'}} {{ obj | json}}
  • 15. Understanding Angular Filters • Format Conver Data Filter • currency custom filter • number limiTo • date orderBy • lowercase • uppercase • json
  • 16. View, Controllers and Scope View $scope Controller $scope is the "glue"(ViewModel) between a controller and a view
  • 17. Understanding Controllers • In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope • When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. • A new child scope will be available as an injectable parameter to the Controller's constructor function as $scope.
  • 18. Creating a View and Controller <div class="container" data-ng-controller="SimpleController"> <h3>Adding a Simple Controller</h3> <input type="text" data-ng-model="name" /> <ul> <li data-ng-repeat="cust in customers"> {{ cust.name }} - {{ cust.city}} </li> </ul> </div> Access $scope <script> Basic controller function SimpleController($scope) { $scope.customers = [ {name : 'Dave Jones', city:'Phoenix'}, {name : 'Jamie Riley', city:'Atlanta'}, {name : 'Heedy Wahlin', city:'Chandler'}, {name : 'Thomas Winter', city:'Seattle'}, ]; } </script> So now we have two properties in the scope. The ng-model is going to add a property in the scope called name, and we can actually get to that now in the controller by saying $scope.name
  • 19. Create a Controller in a Module Module that demoApp depends on var demoApp = angular.module('demoApp', []); demoApp.controller('SimpleController', function($scope) { $scope.customers = [ {name : 'Dave Jones', city:'Phoenix'}, {name : 'Jamie Riley', city:'Atlanta'}, {name : 'Heedy Wahlin', city:'Chandler'}, {name : 'Thomas Winter', city:'Seattle'} ]; });
  • 20. Create a Controller in a Module var demoApp = angular.module('demoApp', []); demoApp.controller('SimpleController', ['$scope', function(scope){ scope.customers = [ {name : 'Dave Jones', city:'Phoenix'}, {name : 'Jamie Riley', city:'Atlanta'}, {name : 'Heedy Wahlin', city:'Chandler'}, {name : 'Thomas Winter', city:'Seattle'} ]; }]);
  • 21. Create Multi Controller in a Module var demoApp = angular.module('demoApp', []); var controllers = {}; controllers.SimpleController = function($scope) { …… }; controllers.SimpleController2 = function($scope) { …… }; demoApp.controller(controllers);
  • 22. The Role of Factories var demoApp = angular.module('demoApp', []) .factory('simpleFactory', function(){ var factory = {}; var customers = [………]; factory.getCustomers = function(){ return customers; }; return factory; }).controller('SimpleController', function($scope, simpleFactory) { $scope.customers = simpleFactory.getCustomers(); }); Factory injected into controller at runtime
  • 23. Create Custom Directive angular.module('docsSimpleDirective', []).controller('Controller', function($scope) { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }).directive('myCustomer', function() { return { restrict: 'A', template: 'Name: {{customer.name}} Address: {{customer.address}}' }; }); <div ng-controller="Controller"> <div my-customer></div> </div>
  • 24. $inject • If a function has an $inject property and its value is an array of strings, then the strings represent names of services to be injected into the function. var MyController = function(renamed$scope, renamedGreeter) { ... } MyController['$inject'] = ['$scope', 'greeter'];
  • 25. Value VS. Service VS. Factory VS. Provider • Value • module.value('valueName', valueObj); • Get value from valueObj • Service • module.service( 'serviceName', ServiceFunction ); • Get service from 'new ServiceFunction()'. • Factory • module.factory( 'factoryName', FactoryFunction ); • Get factory from the value that is returned by invoking the FactoryFunction. • Provider • module.provider( 'providerName', ProviderFunction); • Get provider fromnew ProviderFunction().$get()
  • 26. $watch • $watch(watchExpression, listener, [objectEquality]) • Registers a listener callback to be executed whenever the watchExpression changes • $watchCollection(watchExpression, listener) • Shallow watches the properties of an object and fires whenever any of the properties change
  • 27. Reference • AngularJS In 60 Minutes • http://fastandfluid.com/publicdownloads/AngularJSIn60MinutesIsh_DanWahlin_May2 013.pdf • AngularJS • https://angularjs.org/

Hinweis der Redaktion

  1. minify http://jsbin.com/musiqo/edit?html,js,output
  2. http://jsbin.com/lazila/edit
  3. http://jsbin.com/fusefepama/edit http://bennadel.github.io/JavaScript-Demos/demos/watch-vs-watch-collection/