Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
AngularJS
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
gaozhitw
May 28, 2014
130
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
AngularJS
gaozhitw
May 28, 2014
Featured
See All Featured
For a Future-Friendly Web
brad_frost
184
10k
Collaborative Software Design: How to facilitate domain modelling decisions
baasie
1
340
We Have a Design System, Now What?
morganepeng
55
8.4k
4 Signs Your Business is Dying
shpigford
187
23k
Docker and Python
trallard
47
4.2k
Reflections from 52 weeks, 52 projects
jeffersonlam
356
22k
Visualization
eitanlees
153
17k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
28
3.7k
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
710
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
20k
Building a A Zero-Code AI SEO Workflow
portentint
PRO
0
780
How to make the Groovebox
asonas
2
2.5k
Transcript
AngularJS 2014.05.28
介紹 • 開發於2009年 • Open Source Javascript Library(MIT授權) • 專⾨門為⼤大型CURD專案所開發
• 由Google維護
特點 • Two-Way Data Binding • Module Dependency Injection •
宣告式語法Directive(HTML的元素、屬性、註解) • 採⽤用MVC Design Pattern • DOM Templates • Single Page Application(SPA)
Angular Module angular.module(‘module_name’, [‘inject_module1’, ‘inject_module2’]); 例: angular.module(‘MyApp’, [‘ngRouter’, ‘ngSanitize’]); 以dependency
Injection概念,將個Module分離, 需要使⽤用時才Inject
Angular Controller 以function⽅方式 function MyCtrl($scope){ do_something; } 缺點:容易污染Global環境、Minify後會有問題
以Module⽅方式 var MyCtrlMod = angular.module(‘MyCtrlModule’, []); MyCtrlMod.controller(‘MyCtrl’, function($scope){ do_something; });
缺點:Minify後,仍然會有問題
以Module⽅方式(官⽅方建議寫法) MyCtrlMod.controller(‘MyCtrl’, [‘$scope’, function($scope){ do_something; }]);
⽀支持Cascade寫法 angular.module(‘MyCtrlModule’, []) .controller(‘MyCtrl’, [$scope, function($scope){ do_something; }]) .controller(‘MyCtrl2’,….. …..
}]);
起⼿手式 • 先宣告⼀一個Application主要Module • 在宣告⼀一個(或數個)Controller Module • 在Controller Module內宣告數個Controller •
在HTML上宣告ng-app、ng-controller attribute
例(javascript部分): angular.module(‘MyApp’, [‘ngRouter', ‘ngSanitize’, ‘MyCtrlModule’]); angular.module(‘MyCtrlModule’, []) .controller(‘MyCtrl’, [‘$scope’, function($scope){
$scope.body = ‘我是內容’; }]);
例(html部分): <html ng-app=“MyApp”> <head> <title>DEMO</title> </head> <body ng-controller=“MyCtrl”> {{body}} </body>
</html>
Two-Way Data Binding • AngularJS利⽤用雙向結繫的⽅方式,來實現View與 Model之間的資料交換 • Controller則作為View與Model之間的協調⼯工作
Data Binding 假設Controller內有⼀一個$scope property “body” $scope.body = ‘content’; 結繫到View Render的⽅方式(One-Way):
• 利⽤用兩個⼤大括號{{body}} • 利⽤用ng-bing Directive 如:<span ng-bind=“body”></span> 前者在Angular compile完成前,會看到{{body}}的字串,若不想讓使⽤用者看 到compile完成前的畫⾯面,建議使⽤用第⼆二種⽅方式
結繫到Form Element的⽅方式(Two-Way): 利⽤用ng-model Directive,如: JS: $scope.inputText = ‘XD’; HTML: <input
type=“text” ng-model=“inputText” /> 當使⽤用者在input輸⼊入⽂文字後,將會⽴立即改變$scope.inputText的 值 ⽽而在HTML上若有 {{inputText}} 也將⽴立即render為新的資料
Scope Inheritance • 所有Scope都繼承⾄至rootScope • Child Scope可取得(繼承)Parent Scope的 Property與Method •
來⾃自Javascript prototype inheritance概念
rootScope Scope Child Scope Child Scope
rootScope Scope Child Scope Child Scope $scope.title = ‘XD’
rootScope Scope Child Scope Child Scope $scope.title = ‘XD’ HTML
View: {{title}} (One-Way Data Binding)
rootScope Scope Child Scope Child Scope $scope.title = ‘XD’ HTML
Form Input: ng-model=“title” (Two-Way Data Binding)
rootScope Scope Child Scope Child Scope $scope.title = ‘XD’ HTML
Form Input: ng-model=“title” (Two-Way Data Binding) 建⽴立$scope.title = ‘XDD’ XD XDD <input type=“text” ng-model=“title” />
rootScope Scope Child Scope Child Scope $scope.title = ‘XD’ HTML
Form Input: ng-model=“title” (Two-Way Data Binding) XD <input type=“text” ng-model=“title” /> 解法⼀一: <input type=“text” ng-model=“$parent.$parent.title” />
rootScope Scope Child Scope Child Scope $scope.formData = {title: ‘XD’};
HTML Form Input: ng-model=“title” (Two-Way Data Binding) XD <input type=“text” ng-model=“title” /> 解法⼆二:(推薦) <input type=“text” ng-model=“formData.title” />
Scope Watch $scope.$watch(watchExpression, [listener], [objectEquality]) • watchExpression(string or function): (scope
property) ex: $scope.$watch(‘body’); • listener(function): (callback function) • objectEquality(boolean): 深⼊入監看Object內容是 否相等
範例: MyCtrlMod.controller(‘ExCtrl’, [$scope, function($scope){ $scope.demo = ‘example’; $scope.obj =
{ obj1: ‘objExample1’, obj2: ‘objExample2’ }; $scope.watch(‘demo’, function(){ do_something; }); $scope.watch(‘obj’, function(){ do_something; }, true); }]);
需要注意的地⽅方: watch在angular compile完成後,會先動作⼀一次, 若只想在property變更時才動做,可在callback function內加⼊入: $scope.$watch(‘example’, function(newValue, oldValue)){ if(newValue ===
oldValue){ return; } do_something; } watch的callback function還有第三個可選的參數,可傳⼊入scope 進⾏行所需的操作,例: $scope.$watch(‘example’, function(newValue, oldValue, scope)..
Angular Directive 常⾒見(使⽤用)Angular內建Directive: • ngApp • ngController • ngBind •
ngRepeat、ngInit • ngShow、ngHide • ngIf • ngClass • ngClick、ngChange、ngKeydown、ngKeypress…. • ngSubmit
ngRepeat ngRepeat可⽤用來將Array或Object內的資料,呈現在 經常需重複DOM的地⽅方(類似for、while) 例: 假設我們利⽤用XHR取來⼀一段JSON並解析成Object $scope.nameList = { name1: ‘⼤大明’,
name2: ‘⼩小偉’, name3: ‘阿忘’ };
<html> ….. <body> <div ng-repeat=“name in nameList”> {{name}} </div> </body>
</html> —————————————————————— ⼤大明 ⼩小偉 阿忘
ngRepeat時有幾個常⾒見的變數可取⽤用: $index: ⺫⽬目前repeat的索引 $first 假如⺫⽬目前repeat的元素為第⼀一個 回傳true $last: 假如⺫⽬目前repeat的元素為最後⼀一個 回傳true $even:
$index為偶數時 回傳true $odd: $index為奇數時 回傳true
ngInit 經常與ngRepeat搭配使⽤用,可⽤用來初始化⼀一些變數 例: HTML: <div ng-repeat=“name in nameList” ng-init=“init($index)”> {{name}}
</div> JS: $scope.nameNo = []; $scope.init = function($index){ $scope.nameNo.push($index); }
ngShow / ngHide • 假如ngShow結繫到的property為true,則CSS display: normal; 顯⽰示該Element • 假如ngHide結繫到的property為true,則CSS
display: none; 隱藏該Element 例: $scope.showElement = true; <div ng-show=“showElement”></div>
ngIf ngIf結繫到的property為true時,該Element(DOM)才render 例: <div> <span>XD</span> <div ng-if=‘detect’> <span>XDD</span> </div> </div>
$scope.detect = false; 實際render <div> <span>XD</span> </div>
ngIf需注意的地⽅方: ngIf Directive會建⽴立⼀一個child scope,要特別注意 Two-Way Data Binding時的問題。
ngClass 結繫到的property為true時,寫⼊入className到該 Element的class attribute 例: <div class=“mo” ng-class=“{co: addco, do:
adddo}”></div> $scope.addco = true; $scope.adddo = false; render: <div class=“mo co”></div>
Event Directive ngClick、ngChange…… 可以結繫到method,如: $scope.action = function($event){ do_something };
<button type=“button” ng-click=“action($event)”></button> 可選擇性傳⼊入$event 引數,取得⼀一些event的屬性
ngSubmit 可結繫到處理form的method,如: $scope.formSubmit = function(){ do_something; }; <form ng-submit=“formSubmit()”> <input
type=“text” value=“XD” /> <button type=“submit”>Submit</button> </form>
Angular Service 常⾒見內建Service: • $filter • $http • $window •
$location • $document • $timeout • $interval
$filter 可⽤用來過濾不需要的內容,或進⾏行某些資料格式化 有兩種使⽤用⽅方式: • 直接在HTML Template Binding中使⽤用 • 將Service注⼊入Javascript中使⽤用
• 直接在HTML Template Binding中使⽤用 例: <div ng-repeat=“name in nameList |
filter: [String|Object|function(value)]”> {{name}} </div> • (String) Array或Object內有符合的String才會被回傳 • (Object) 如{no: “1”, name: “wayne”},將回傳符合條件的Object • (function) 會將要判斷的值,當成第⼀一個引數傳進method,假如 method回傳true,則回傳該值。 在HTML Template中,也可將資料格式化,如: {{ dateObj | date : ‘yyyy-MM-dd’ }} {{ Obj | json }}
• 將Service注⼊入Javascript中使⽤用 MyCtrlMod.controller(‘MyCtrl’, [‘$scope’, ‘$filter’, function($scope, $filter){ $filer(‘filter’)(array, function(value){ if(….){
return false; //過濾掉 } return true; }); }]); 也能做資料格式化,如: $filter(‘json’)(Object); $filter(‘date’)(date, format);
$http AngularJS中⽤用來發出Http Resquest的Service MyCtrlMod.controller(‘MyCtrl’, [‘$scope’, ‘$http’, function($scope, $http){ $http({method: ‘GET’,
url: ‘/someUrl’}) .success(function(data, status, headers, config){ do_something; }).error(function(data, status, headers, config){ do_something; }); }]); 通常在Web Application開發時,Http Request通常不會⽤用到如此細鎖的操 作,所以Angular官⽅方有另外將這些操作進⾏行⾼高階抽象化成⼀一個module “ngResource”,再⼤大部份的情況下使⽤用該module操作即可。
$window 參考⾄至瀏覽器原⽣生的window object,因window是 javascript全域性的物件,對於AngularJS的可測試 性會產⽣生⼀一些問題,所以官⽅方將其打包成AngularJS 的Service $window。 例: $window.alert(‘Hello World’);
$location • ⽤用來處理監看瀏覽器網址列、改變網址等操作, 基於原⽣生的window.location • 若有使⽤用ngRoute,設置routes,常會搭配 $location Service來變更網址history
$document • 由原⽣生window.document物件打包⽽而成的Service • 可⽤用AngularJS內建的jqLite,做簡單的DOM操作 或Event Listener 例: MyCtrlMod.controller(‘MyCtrl’, [‘$scope’,
‘$document’, function($scope, $document){ $document.on(‘scroll’, function(){ do_something; }); }]);
$timeout / $interval 這組Service是打包原⽣生Javascript得setTimeout與 setInterval 例: MyCtrlMod.controller(‘MyCtrl’, [‘$scope’, ‘$timeout’, ‘$interval’,
function($scope, $timeout, $interval){ $timeout(function(){ do_something; }, 2000); $interval(function(){ do_something; }, 2000, 5); }]);
Scope Apply 為什麼需要將Native Javascript打包成Service? 舉setTimeout為例: MyCtrlMod.controller(‘MyCtrl’, [‘$scope’, function($scope){ $scope.face =
‘XD’; setTimeout(function(){ $scope.face = ‘:)’; }, 2000); $scope.$watch(‘face’, function(newValue, oldValue){ if(newValue === oldValue){ return }; alert(‘smile’); }); }]); HTML Template binding: <div>{{face}}</div>
在$scope中有個$digest method,⽤用來通知watch及 binding,$scope的值改變了,⽽而我們通常不會直接呼叫 $scope.$digest(),⽽而是透過$scope.$apply()去通知 $scope.$digest() 修正: MyCtrlMod.controller(‘MyCtrl’, [‘$scope’, function($scope){ $scope.face
= ‘XD’; setTimeout(function(){ $scope.face = ‘:)’; $scope.$apply(); }, 2000); $scope.$watch(‘face’, function(){ alert(‘smile’); }); }]);
打包成Service的⽤用意: • 包含調⽤用$scope.$apply() • 使code可測試 因此最後可改為: MyCtrlMod.controller(‘MyCtrl’, [‘$scope’, ‘$timeout’, function($scope,
$timeout){ $scope.face = ‘XD’; $timeout(function(){ $scope.face = ‘:)’; }, 2000); $scope.$watch(‘face’, function(){ alert(‘smile’); }); }]);
ngResource Module • ngResource module包含了⼀一個$resource Service 將$http Service打包成更加抽象⽅方便使⽤用的XHR Service •
基於RESTful的概念去設計 使⽤用: <script src=“angular-resource.js”></script> angular.module(‘MyApp’, [‘MyCtrlModule’, ‘MyServiceModule’]);
創建⼀一個Service Module angular.module(‘MyServiceModule’, [‘ngResource’]) .factory(‘MyData’, [‘$resource’, function($resource){ var getNameData =
$resource(‘/someUrl’); return {getName: getNameData}; }]); 在Controller內使⽤用 angular.module(‘MyCtrlModule’, []) .controller(‘MyCtrl’, [‘$scope’, ‘MyData’, function($scope, MyData){ var nameList = MyData.getName.get({}, function(){ do_success_something; $scope.nameList = nameList; }, function(){ do_error_something; }); }]);
預設RESTful Method: {‘get’: {method: ‘GET’}, ‘save’: {method: ‘POST’}, ‘query’: {method:
‘GET’, isArray: true}, ‘reomve: {method: ‘DETELE’}, ‘detele’: {method: ‘DETELE’} }; ⾃自⾏行定義Method: $resource(‘/someUrl’, {}, { someMethod: {method: ‘GET’, isArray: true, timeout: 30000, ……} }); 可變網址參數: $resource(‘/someUrl/:Id’, {Id: 5}); MyData.getName.get({Id: 5}, function(){…..}, function(){.….});
~END~