-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathAngular Fundamentals=Joe Eames;Note=Erxin.txt
883 lines (689 loc) · 26.3 KB
/
Angular Fundamentals=Joe Eames;Note=Erxin.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
Angular Fundamentals=Joe Eames & Jim Cooper;Note=Erxin
# introduction
- module agenda
what, why, how
- hello world
- EventReg angular event registration site
- course update, use a git repository
https://github.com/jeeames/AngularFundamentalsFiles
- Angular JS
MV* javascript framework
angular wants you to only manipulate DOM only inside of directives
in directives you could use jquery, zepto or any other library
opinionated software, have a strong right or wrong to do something
http://gettingreal.37signals.com/ch04_Make_Opinionated_Software.php
the best software have a vision, the best software take side
+ MV* framework
Mode, View, * stand for Controller/Presenter/ViewModel/???, angular use a controller
+ angular is open source, build by google team
+ comprehensive
+ testable, not only support unit test but also support end to end integrate test
Karma, is test tool which is built by the team
+ extends html vocabulary, directives are designed for manipulate DOM, html is design for application not for documents
<input id="username" type="text" focus/> //will fit for non html5 supported browsers
<multiStateButton id="button1"/>
<userTitle id="userTitle" user="currentUser"/>
+ Forward thinking
web components, makes you to truly encapsulated components widgets for your page, encapsulating html, javascript and css
http://www.w3.org/TR/components-intro/
object.observe, lets you watch an object or property on a javascript object for changes and react to those
http://wiki.ecmascript.org/doku.php?id=harmony.observe
http://angularjs.org, offical site, use a lot of develop link
- angular architecture
two way binding
dirty checking
dependency injection http://en.wikipedia.org/wiki/Dependency_injection
+ angular components
controllers, contain both logic and state, its the center components
views/directives, controller communicate with these
services, communicate with controllers
- hello word application
//index.html
<!doctype html>
<html ng-app="app"> //this is a application name for your app
<head>
</head>
<body>
<h1 ng-controller="HelloWorldCtrl">{{hellowMessage}}</h1>
<script src="https://code.angularjs.org/1.4.0/angular.js"></script>
<script type="text/javascript">
//first is the application name and dependented modules, controller required controller name and functions
angular.module('app', []).controller('HelloWorldCtrl', function($scope){
$scope.helloMessage = "hello world";
};
</body>
</html>
- angular EventReg for creating and viewing Angular events or conferences and for viewing and voting for the session available at these events. So the first major feature of EventReg is ability
List of Angular Events
event details
Create new Events & Sessions
Edit events & sessions
login
server, demo with node server or asp.net mvc server
- use twitter bootstrap to make the slightly easier
- angular version, 1.0.5
- command shell, bash shell
Webstorm, it also integrate with Karma test tool
Web server
# Angular Controllers & Markup
- agenda
controllers & Scope
Markup & Binding
use and receive events
Filters
Validation
- introduction
demo project could be download from github
app
css
bootstrap.css
img
js
controllers
services
app.js
directives.js
filters.js
lib //for third-party javascript library
angular
bootstrap.js
bootstrap.min.js
jquery.min.js
angularjs.js
favicon.ico
script
test
README.md
server.bat
server.sh //use to start the server
//app.js
var eventsApp = angular.module('eventsApp', []);
- Quiz
- creating nodejs server
create a express webserver install the module dependencies
$ npm install express[@version]
$ npm install body-parser[@version]
//web-server.js
var express = require('express');
var path = require('path')
var app = express();
var rootPath = path.normalize(__dirname + '/../');
//test express service directly use all the files directly under the location
app.use(expresss.static(rootPath + '/app'));
app.listen(8000);
console.log('listening on port 8000...');
//start the server
$ server.sh
- creating asp.net server, use iis to host the service. add website and give a name and add the demo project path
- controllers & scope
controller -> scope <-> view
scope is used to expose module to the view, but the scope is not the model. view could call functions access properties from the scope. model is the data put into the scope
we can use methods on the scope to modify the model perhapes events fired by the view. or use two way bindings
- demo controllers
// /app/EventDetails.html
<!doctype html>
<html lang="en" ng-app="eventsApp"> //we have name the app in the //app.js angular will use relative js
<head>
<meta charset="utf-8">
<title>Event registration</title>
<link rel="stylesheet" href="/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/css/app.css"/>
</link rel="stylesheet" href="/css/app.css"/>
</head>
<body>
<div class="container">
<div class="navbar">
<ul class="nav">
</ul>
</div>
//add controller to tell angular this div is managed by the controller
<div ng-controller="EventController">
<img ng-src="{{event.imageUrl}}/> //the ng-src is used to delay the process of the text and to let angular have a chance to replace the text. to prevent when the DOM loaded the browser will kick a request for the image which will lead to a 404 fail
{{event.name}}<br/>
{{event.date}}<br/>
{{event.time}}
<hr/>
<h3> sessions </h3>
<ul>
<li ng-repeat="session in event.sessions">{{session.name}}</li>
</ul>
</div>
</div>
<script src="/lib/jquery.min.js"></script>
<script src="/lib/underscore-1.4.4.min.js"></script>
<script src="/lib/bootstrap.min.js"></script>
<script src="/js/angular.js"><script>
<script src="/js/app.js"></script>
<script src="/app/js/controllers/EventController"></script>
</body>
<html>
// /aap/js/controllers/EventController.js
'use strict';
eventApp.controller('EventController', function EventController($scope){
$scope.event = {
name:"angular boot",
date:"1/1/2013",
time:"10:30 am",
imageUrl:xxx
sessions:[
{name:'x'},
{name:'y'}
]
};
});
ng-src,
ng-app,
ng-repeat are all angular directives
- displaying repeating information
check the previous code sample about the session parts
- handling events
<li ng-repeat="session in event.sessions">
...
<div ng-click="upVoteSession(session)"></div>
//add relative event handler into the scope
$scope.upVoteSession = function(session){
session.upVoteSession ++;
};
</li>
- buit-in directives
new html functionality, there are four ways to write out directives
<ng-form/>
<div ng-form/>
<div class="ng-form"/>
the forth way to write out a directives is use html comment
- event directives
ngClick
ngDblClick
ngMousedown
ngMouseenter
ngMouseleave
ngMousemove
ngMouseover
ngMouseup
ngChange, will detect lots of change event for html elemnts
<input type="checkbox" ng-change="handleChange()" ng-mode="property"/>
ng-change also required ng-mode also added into the same tag to active, it is relative to two way binding
- other directives
ngApp
ngBind
ngBindTemplate
ngBindHtml
ngBindHtmlUnsafe
+ ngBind diretive
<tag>{{scope-property.value}}</tag>
equal to
<tag ng-bind="scope-property.value/>
+ ngBindTemplate
<tag ng-bind-template="{{property0}} {{property1}} ..."/>
there are other ways to do it
+ the other bindings we need to reference another angular script
<script src="/js/angular/angular-sanitize.js"></script>
add dependencies to the eventApp module to the sanitize module
var eventsApp = angular.module('eventsApp', ['ngSanitize'])
then we could use the ng-bind-html directive
<div ng-bind-html="snippet">some title</div>
add snippet property into the scope
$scope.snippet = "<span style="color:red"> hi there</span>";
bind html directive will remove any dangerous css and only attach the html to the tag
the displayed content will be
<div ng-bind-html="snippet" class="ng-binding">
<span> hi there</span>
</div>
ngBindHtmlUnsafe is deperacted
ngHide
ngShow
<tag ngHide="boolValue">...</tag> will control the hide and show base on the bool value of the scope
this is a good example for not manipulate your dom in controller, only use directive to control the DOM
ngCloak, this is used to hide the content html and let angular to replace the directive and then show the content
we need to add the clock css from the angular website
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], [ng-cloak], [x-ng-cloak]{
display:none;
}
<body ng-cloak>
...
</body>
ngStyle directive
<tag ng-style="custom-style">...</tag>
set the property of the scope to some css
$scope.custom-style = {color:'red'}
ngClass, ngClassEven, ngClassOdd, there are all likes the ngStyle, class is used to replace the class name from the scope property
- other directives part 2
ngDisabled
ngChecked
ngMultiple
ngReadonly
ngSelected
ngForm, normal html form could not be nested, ngForm allow to create nested html form
ngSubmit, relative ngForm
ngHref, for anchor tag
ngSrc, for img
ngNonBindable, tell angular do not parse inside this binding
- IE restrictions with angular for old version of IE
polyfill JSON.stringify
http://www.codeproject.com/Articles/369858/Writing-polyfills-in-Javascript
http://stackoverflow.com/questions/10963723/json-polyfill-json-2-or-json-3
http://bestiejs.github.io/json3/
No NG tags, IE have custom tag restriction, use attribute form or class form
- Expressions
code snippets javascript
{{expression}}
but expression is not the full javascript engine, such as can't access built-in Math functions
- filters
modifying output
formatting
sorting dataset
filtering dataset
+ using filter in angular
{{expression | filter}}
the expression data will send to the filter and use the filter output as binding data
- built-in filters
uppercase, turn the input string to uppercase
lowercase, turn the input string lowercase
they take string data either upper or lower cases
{{name|uppercase}}
number, use to format number
{{3.14159 | number:2}} //only get output 3.14
currency, will use the local currency symbol to display the number
{{3.14 | currency}} //will display $3.14 in US region
date, for formatting date
{{date | date:medium }}
json, most is used for debugging
{{obj | json}}
orderBy, limitTo, filter are used to work with ngRepeat directive
<div ng-repeat="session in event.sessions | orderBy: sortorder">
...
goto the scope add sortorder property to specify which property is used to sort
$scope.sortorder = "name"; //name is the propoerty name of the session add '-' to use decrease sort
use selecter to control the sortorder from html view by
<select ng-mode="sortorder">
<option selected value="name">Name</option>
<option selected value="-upVoteSession">Votes</option>
</selection>
if we only want to show two items at each time we could use limit filter
<div ng-repeat="session in event.sessions | orderBy: sortorder | limitTo:2 ">
use filter directive to filter the data base on the given value
<select ng-mode="query">
<option selected value="">All</option>
<option selected value="introducton">introduction</option>
<option selected value="advanced">advanced</option>
</select>
<div ng-repeat="session in event.sessions | orderBy: sortorder | filter:query">
by default angular don't required the field name to seach, it will search entire dataset for the specify filter. to specify field name for the filter we need to use
<select ng-mode="query.field_name">
- writing custom filters
module.filter('filter-name', function(){
return function(input /*, filter parameter*/){
//modify input
return modified-output;
}
});
eventsApp.filter('duration', function(){
return function(duration){
switch(duration){
case 1:
return "half hour";
case 2:
return "1 hour";
}
}
});
reference script
<script src="/js/controllers/EventController.js></script>
use the custom filter
{{hour|duration}}
- two way binding, is base on the model directive, it works with three html elements
ngModel, the model directive you could automatic update/retrieve data from the html elements, input, select and textarea
<input type="text" ng-model="object.property" />
- demo two way binding
<form>
<fieldset>
<label for="eventName">Event name</label>
<input id="eventName" ng-model="event.name" type="text" placeholder="Name of your event"/>
<input id="img" ng-mode="imageUrl" type="text"/>
...
<img ng-src="{{event.imageUrl}}/>
use ng-mode directive we don't required to create event property to the scope which will automatic add the property to complete the binding
eventApp.controller('EditEventController', function EditEventController($scope){
});
control navigation in js by assign path to the window.location property
- validation
Required, field, <input required ../>
ngPattern, meat of validation
Form properties
CSS Classes, supplied by angular to indicate the validation results
use ngPattern
<input ng-pattern="js-reglar-expression-to-filter"
<form name="newEventForm"/>
<button stype="submit" ng-disable="newEventForm.$invalid" ng-click="saveEvent(event, newEventForm)"/>
</form>
$scope.saveEvent = function(event, newEventForm){
if(newEventForm.$valid){
....
}
}
we could use the automatic added removed style for the validation field to add custom style for the form input fields
<style> input.ng-invalid.ng-dirty { background-color:pink}</style>
# Creating and Using angular services
- what is a service
the term service is overloaded
angular service is a worker object, it not necessary access wire, often stateless
built-in and custom services
navigation
ajax
custom services
reusable business object
break application easy to maintain
SRP, single responsible principle, SOLID principle
dependency injection into controller
testable make your code, thanks for dependency injection, use mock replace
when you create a service, you need to register the service
- creating your first custom service
//EventController.js
eventApp.controller('EventController', EventController($scope, eventData){
$scope.sortorder = 'name';
$scope.event = eventData.event;
});
+ add services directory under the js folder
/app/js/services
all built in angular service will start with $, we should not name our service with dollar signe
// /app/js/services/EventData.js
eventsApp.factory('eventData', function(){
return {
event:{
...//event data
}
};
});
//factory method paramter is the name of the service and init method
//factory method is used to register angular service into the application
we could use the created eventData service to inject into the EventController from the parameter
we also need to add the service script file into the page file
<script src="/js/service/EventController.js"></script>
- another custom service example
+ create a EditProfile.html page
<div ng-controller="EditProfileController">
..
</div>
use the ng-controller directive to bind the controller to page
+ create EditProfileCOntroller.js
eventApp.controller('EditProfileController', function EditProfileCOntroller($scope){
$scope.user = {};
$scope.getGravatarUrl = function(email){
return ...
}
});
+ use the getGravatarUrl function in the view
<img ng-src="{{getGravatarUrl(user.emailAddress)}}/>
...
<input id="mailAddress" type="email" ng-model="user.emailAddress"/>
+ create a new service for the controller get gravatar logic
//GravatarUrlBuilder.js
eventApp.factory('gravatarUrlBuilder', function(){
return {
buildGravatarUrl: function(email){
return 'http://www.gravatar.com/avatar/'+md5(email)+'.jpg?s=200&r=g';
}
}
});
+ use the service method in the controller
eventApp.controller('EditProfileController', function EditProfileCOntroller($scope){
$scope.user = {};
$scope.getGravatarUrl = function(email, gravatarUrlBuilder){
return gravatarUrlBuilder.buildGravatarUrl(email);
}
});
+ add the service js reference into the view html
<script src="/js/services/GravatarUrlBuilder.js"></script>
- introduction to built-in angular services
+ common used
$http,
$resource
$anchorScroll
$cacheFactory
$compile
$parse
$locale
$timeout
$exceptionHandler
$filter
$cookieStore
+ less used
$interpolate
$log
$rootScope
$window
$document
$rootElement
+ route relative service
$rout
$routeParams
$location
+ test relative service
$httpBackend
$controller
- using angular's $http service
+ update the eventData service
//EventData.js
eventsApp.factory('eventData', function($http, $log){
return {
getEvent: function(successcb){
$http({
method:'GET',
url: '/data/event/1'
})
.success(function(data, status, headers, config){
successcb(data);
})
.error(function(data, status, headers, config){
$log.warn(data, status, headers(), config);
});
}
}
});
+ update the event controller to call the event service method
eventsApp.controller('EventController',
function EventController($scope, eventData){
$scope.sortorder = 'name';
$scope.event = eventData.getEvent(function(event){
$scope.event = event;
});
});
- Updating a node server for json requests, we require a module called body-parser which could be installed by npm
// /scripts/web-server.js for not node.js script
var express = require('EXPRESS');
var path = require('path');
var events = require('./eventsController');
var app = express();
var rootPath = path.normalize(__dirname + '/.../');
var bodyParser = require('body-parser');
app.use(express.static(rootPath + '/app'));
app.get('/data/event/:id', events.get);
app.post('/data/event/:id', events.save);
app.listen(8000);
console.log('Listening on port' + 8000 + '...');
// add event cotnroller script /scripts/eventsContrller.js
var fs = require('fs');
module.exports.get = function(req, res){
var event = fs.readFileSync('app/data/event/' + req.params.id + '.json', 'utf8');
res.setHeader('Content-Type', 'application/json');
res.send(event);
};
module.exports.save = function(req, res){
var event = req.body;
fs.writeFileSync('app/data/event/' + req.params.id + '.json', JSON.stringify(event));
res.send(event);
}
- updating an IIS server for JSON requests
+ create a asp.net MVC4 web API project
+ add EventController.cs
public class EventController: ApiController
{
public JToken Get(string id = null)
{
var path = System.Web.HostingEnvironment.MapPath("/");
return JObject.Parse(System.IO.File.ReadAllText(path + "../app/data/event/" + id + ".json"));
}
public void Post(string id, JObject eventData)
{
var path = System.Web.Hosting(HostingEnvironment.MapPath("/"));
System.IO.File.WriteAllText(path + "../app/data/event/" + id + ".json", eventData.ToString(Formatting.None));
}
}
+ add default rout to the api configure
//WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controler}/{id}",
defaults: new {id = RouteParameter.Optional}
);
}
+ add the application to iis, make sure your iis contain a asp.net 4 application pool
right click the website and add an application select the asp.net version and choose the physical address of the compiled assembly path
- using $http promises, use promise method. http service call return a promise method
//EventData.js
eventsApp.factory('eventData', function($http, $log){
return {
getEvent: function(){
return $http({
method:'GET',
url: '/data/event/1'
});
}
}
});
//in the controller we could use the return promise object
//EventController.js
eventApp.controller('EventController',
function EventController($scope, eventData, $log){
$scope.sortorder = 'name;
eventData.getEvent()
.success(function(event){$scope.event = event;})
.error(function(event){
$log.war(data, status, headers(), config);
});
}
);
- using angular's $resource service, it is use same suff as $http, but it assume the webserver use the json data format with ajax call. It means required service support reset api. the resource API doesn't return a promise object. so the return value couldn't directly use then etc. methods. required to use $promise.then to use then method
//EventData.js
eventsApp.factory('eventData', function($resource){
return {
getEvent:function(){
//parameters: url, default-value replace use .get method to get the resource object with the replace parameter
return $resource('/data/event/:id', {id:'@id'}).get({id:1});
}
};
});
+ to use resource service we need to add dependency to the resource module
//app.js
var eventsApp = angular.module('eventsApp', ['ngResource']);
//EventDetail.html required to include the angular-resource.js
</script src='/lib/angular/angular-resource.js"></script>
+ use the resource api in the event controller
eventsApp.controller('EventController', function EventController($scope, eventData){
$scope.sortorder = 'name';
eventData.getEvent()
.$promise.then(
function(event){$scpe.event = event;}, //success
function(response){$console.log(response);} //failure
)
.catch(function(reponse){console.log(response)});
$scope.upVoteSession = function(session){
session.upVoteCount++;
};
});
+ saving data with $resource
//EventData.js
eventsApp.factory('eventData', function($resource){
resource = $resource('/data/event/:id', {id:'@id'});
return {
getEvent: function(){
return resource.get({id:1});
},
save:function(event){
return resource.save(event);
}
};
});
use the save method in the eventController
//EditEventController.js
eventsApp.controller('EditEventController',
function EditEventController($scope, eventData){
$scope.saveEvent = function (event, newEventForm){
if(newEventForm.$valid){
eventData.save(event).$promise.then(
function(response){console.log('success', response},
function(response){console.log('failure', response}
);
}
};
$scope.cancelEvent = function(){
window.location = "/EventDetails.html";
};
}
);
//we also require to reference the angular resource and event data js from the NewEvent.html
<script src="/js/angular/angular-resource.js"></script>
<script src="/js/services/EventData.js"></script>
$resource service is the best for access restful webservice. $http service is used to access non-restful service
ngResource contain the $resource service
- angular's $anchorScroll service
$anchorScroll service is used to take the id from the url hash and scroll the scrollbar to the specify id, call it with
http://www.xxx.com/abc.html##some-id
//EventController.js
$scope.scrollTo = function(){
$anchorScroll();
};
- $cacheFactory service to demo this create a cacheSampleController
//CacheSampleController.js
eventsApp.controller('cacheSampleController',
function CacheSampleController($scope){
}
);
//CacheSample.html
<script src="/js/controllers/CacheSampleController.js"></script>
- $compile service, it is used heavily internal of angular. it is used to parse the html and look for directive and process them
<div ng-controller="CompileSampleController" style="...">
<div id="appendHere"></div>
<br/>
name:<input type="text" ng-model="name"/><br/>
markup:<input type="text" ng-model="markup"/></br>
<button class="btn" ng-click="appendDivToElement(markup)">Append</button>
</div>
eventsApp.controller('CompileSampleController', function CacheSampleController($scope, $compile){
$scope.appendDivToElement = funciton(markup){
return $compile(markup)($scope).appendTo(anagular.element("#appendHere"));
}
});
the $compile service is return a function, the context is the $scope, angular.element is similar to jquery
then we type John to the html name text box and <h3>{{name}}</h3> to the markup input box. after click the button the markup content will be compile and attach to the #appendHere div. if the markup contain binding it will works too after appended.
- $parse, it is similar to $compile. $parse is used to evaluated expression and return a function
var fn = $parse('1+2');
console.log(fn());
+ parse with different context
var getter = $parse('event.name');
var context1 = {event:{name:'AngularJS Boot Camp'}}
var context2 = {event:{name:'code camp'}}
getter(context1);
getter(context2);
+ the function return by $parse can be pass func(globalContext, localContext); the localContext will overwrite the globalContext
+ the function return by $parse have an assign property
var setter = getter.assign;
//the assign property is also a function
setter(context2, 'Code retreat');
//the propert of context2.event.name is updated
- $local service is used for localization for date and time
<h3>{{myDate |date:myFormat}}</h3>
$scope.myDate = Date.now();
$scope.myFormat = $local.DATETIME_FORMATS.fulldate;
+ change localization need to used localization file. https://code.angularjs.org/version/i18n/
+ reference the download local file then the date time format will be changed
- $timeout service
- $exceptionHandler
- $filter
- $cookieStore
- overview of less common angular services
# Angular Routing
# Creating Custom Angular Directives
# Testing Angular