introduction to angular.js

29
Sayed Ahmed Computer Science and Engineering, BUET, Bangladesh MSc, Computer Science, Canada http://sayed.justetc.net

Upload: skah

Post on 13-Jan-2016

63 views

Category:

Documents


1 download

DESCRIPTION

Sayed Ahmed Computer Science and Engineering, BUET, Bangladesh MSc, Computer Science, Canada http://sayed.justetc.net. Introduction to Angular.JS. Checked on Angular and created the following training video https://www.youtube.com/watch?v=5NAC6DfB1VY - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction to Angular.JS

Sayed Ahmed

Computer Science and Engineering, BUET, BangladeshMSc, Computer Science, Canadahttp://sayed.justetc.net

Page 2: Introduction to Angular.JS

Checked on Angular and created the following training video https://www.youtube.com/watch?v=5NAC6DfB

1VY Partially Read the Book: Mastering Web

Application development in AngularJS Watched the video

Google I/O 2013 - Design Decisions in AngularJS

https://www.youtube.com/watch?v=HCR7i5F5L8c

Page 3: Introduction to Angular.JS

Watched this but pretty lightly Introduction to Angular JS

https://www.youtube.com/watch?v=8ILQOFAgaXE Pretty lightly watched

Karl Seamon - Angular Performance - NG-Conf

https://www.youtube.com/watch?v=zyYpHIOrk_Y Tried to watch but did not finish [still in my

tablet] Security with Angular JS

https://www.youtube.com/watch?v=18ifoT-Id54 Testing Strategies for Angular JS

https://www.youtube.com/watch?v=UYVcY9EJcRs

Page 4: Introduction to Angular.JS

MVVM: Such as Angular.JS and Knockout.js http://en.wikipedia.org/wiki/Model_View_ViewMo

del

KnockOut.js http://en.wikipedia.org/wiki/Knockout.js

Presentation Model by Martin Fowler http://martinfowler.com/eaaDev/

PresentationModel.html (theory behind: MVVM)

Page 5: Introduction to Angular.JS

Why Angular? and Why not Angular

10 reasons why use angular? http://www.sitepoint.com/10-reasons-use-angularjs/

Why Does Angular.js Rock? http://angular-tips.com/blog/2013/08/why-does-angular-dot-js-rock/

Check the total article and esp the section: Why not Angular, Why not Backbone, Why not Ember

https://moot.it/blog/technology/frameworkless-javascript.html 

These articles do worth reading: http://angular-tips.com/blog/archives/

Bite-sized web development training with AngularJS https://egghead.io/

Page 6: Introduction to Angular.JS

Mastering Web Application Development with AngularJS http://www.packtpub.com/angularjs-web-

application-development/book CRUD Application Demo with Angular

https://github.com/angular-app/angular-app Angular.JS Wiki

https://github.com/angular/angular.js/wiki

 

Page 7: Introduction to Angular.JS

Recent AngularJS also makes use of regular expressions for form validations such as:

<input type="text" ng-pattern="[a-zA-Z]" />

Page 8: Introduction to Angular.JS

AngularJS will work with the latest versions of Chrome, Firefox, Safari, and Opera, as well as Internet Explorer version 8, 9, and 10. You will need to do some extra work for IE8

To make AngularJS Work with IE8 use the following

<html ng-app="application_name" id="application_name">

Though ng-app="application_name" is sufficient for the other browsers as mentioned in point 1; for IE 8, id attribute is also required

We cannot make IE to recognize and include templates in the following manner

<ng-include="'myInclude.tpl.html'"></ng-include>

Though, we can take a different strategy to make IE8 recognize and include templates by using

<div ng-include="'myInclude.tpl.html'"></div>

Page 9: Introduction to Angular.JS

we have to make IE8 recognize <ng-include=""> to be able to use this custom tag to include templates. We can do that by using

<head><!--[if lte IE 8]><script>document.createElement('ng-include');document.createElement('ng-view');. . .<![endif]--></head>

Supporting IE7 for AngularJSYou need to do everything that you did for IE8.AngularJS was not tested with IE7; so you need to adjust stuff as they come alongIE7 does not have many APIs commonly present in web-browsers such as JSON APIYou will need libraries such as http://bestiejs.github.io/json3/ to be included in your application to support JSON

5. IE6 is not supported

Page 10: Introduction to Angular.JS

The Issue and Why Optimize In general, the landing web-page should load fast to have a good

impression of the application/web-site. However, that usually requires some extra work and tuning.

If you have developed a single page web-application with AngularJS or you have developed a single page web-based mobile application with AngularJS, you need to optimize the landing page.

It can be tricky to load and display the first page right; with mobile this becomes more tricky. And with Angular, you have to download additional Angular libraries that will inject information or data to make the page look right. If not done right, you may end up showing the templates, and lots of curly braces ( {{ user.name}} ) to your users.

For rescue, there are three helps ng-bind : Angular Directive ng-cloak : Angular Directive AMD : Asynchronous JavaScript Module Loading with Require.js

Page 11: Introduction to Angular.JS

Recommendations: If your first page has lots of dynamic contents, use ng-cloak directive for

the dynamic data/information blocks that will hide those sections before AngularJS can kick in and inject data/information. You can even place it in the body tag.

If your first page has mostly static content, use ng-bind for the static content (i.e where you were using curly braces {{}} ). You can also assign some default values for those static places so that before Angular kicks in the default value will be shown. If you do not provide default values those places will be empty before Angular fills information.

If your page has a mix of dynamic and static contents, you can use ng-cloak, and ng-bind together.

You can use asynchronous loading of JavaScript modules. You can use smaller JS files and link them to the pages where they are required. Now, based on the dependencies the scripts will load asynchronously. However, if a page needs too many of the script files, there will be more network overhead. You need to be smart about dividing and linking those script files. Though, performance gain by this strategy probably is debatable. You probably need to measure the performance gain, and again in real world, is the client ready topay?

Page 12: Introduction to Angular.JS

Another Tip If the page is mostly static, put <script> at the bottom and use ng-

bindIf the page is mostly dynamic, put <script> at the top and use ng-cloak

Examples of using ng-cloak <div ng-controller="" ng-cloak>

<h1>Hello, {{name}}!</h1></div>

Example of using ng-bind <div ng-controller="">

Hello, <span ng-bind="name"></span>!</div>

If you use Require.js to load angular, you cannot use ng-app directive. You need to use angular.bootstrap method from JavaScript instead

Reference: Book: Mastering Web Application Development with AngularJS

Page 13: Introduction to Angular.JS

Optimizing AngularJS Page Loading: Optimizing web-applications for faster performance

often include reducing network activities, reducing send and receive requests over the network/internet, and reducing data downloads. Minification of JavaScript, CSS, and HTML files can help with that. AngularJS kind of forces to write minification safe JavaScript, and writing array styleand annotation based function declaration is recommended.

Creating partial templates and loading related templates in combination may help. Probably, need some experiment and planning before than doing it on the fly. Two ways to preload templates 1. <script> tag 2. $templateCache

Page 14: Introduction to Angular.JS

You may want to read one of our other articles on optimizing landing pages for AngularJS single page applications by usinng ng-cloak, and ng-bind

Using Asynchronous script loader such as Require.Js does not improve the performance a lot [according to the book as listed in the reference section]. Hence, so far, AMD is not recomended with AngularJS

You can check how to use Require.JS in your applications at : http://requirejs.org/docs/start.html .

You may want to use them in non-AngularJS projects. The idea is, you have to have a consistent project directory structure esp for JavaScript files as recommended and specified by Require.Js. In your, HTML file you refer to the main.js file, single entry point for loading JS code. In that main.js, you will use Require.JS esp. require() to load other JS files asynchronously and as required by your application.

Page 15: Introduction to Angular.JS

To use Require.JS with JQuery, you can check the following resource. The adoption may need different considerations for a new project or for adapting existing code for Require.JShttp://requirejs.org/docs/jquery.html

Page 16: Introduction to Angular.JS

Securing Your AngularJS ApplicationsSome security measures can be as follows:

Take security measures at the entry and exit points of data to and from the server Secure the server and prevent unauthorized

access to data, and HTML Encrypt the connection i.e https:// Prevent cross-site scripting (XSS), Prevent cross-site request forgery (XSRF)

attacks Block JSON injections

Page 17: Introduction to Angular.JS

AngularJS Templates Securing:$templateCache caches templates if you want to use this. We need to remove the cache for each user login

The following or similar stuff can helpCache-Control: no-cache, no-store, must-revalidatePragma : no-cacheExpires : 0

Page 18: Introduction to Angular.JS

using https can address the snooping and man in the middle attack

You need to prevent JSON Injection Vulnerabilityto do this, you can add )]}', before your JSON, though not valid JSON but helps to prevent JSON injection vulnerability.

Prevent XSS attack in the client sideAngularJS escapes all HTML in text that is displayed through the ng-bind directive, or template interpolation (that is text in {{curly braces}}).

Page 19: Introduction to Angular.JS

Performance Improvement of AngularJS Applications: Writing Robust AngulaJS Applications

Ideally, you need to measure the performance and apply the strategy based  on the outcome. Your intuition may be wrong unless you verify it against real life situations and measure it. Also, testing the performance on real or sample data may help depending on the Application.

Page 20: Introduction to Angular.JS

That's right, I did not experience it, but the right knowledge is, you need to be careful about using the $digest loop. Too many iterations such as 50 loops or 100 loops may make your applications unresponsive. The numbber of watches inside  the $digest loops, and how fast those watches run also affect performance a lot. You can either reduce the numbber of watches or make the watches faster. You can also monitor memory usage by those watches. Less memory use can make your application faster.

Page 21: Introduction to Angular.JS

ng-repeat directive is also performance sensitive. If you use ng-repeat to work on collections having 100s of items, it may cause performance penalty. So either plan and limit the entries in your collections or write custom directives for the purpose. In either case, do it in such a way so that it causes less performance penalty. You need to measure though.

Page 22: Introduction to Angular.JS

Localization Support in Angular : Writing International Applications in AngularJSUnder the AngularJS library there is a folder i18n where en-us locale related data are kept. If you want to use a different locale you can do it as follows. Notice the script tag with lib/angular/angular-locale_fr-ca.js to support for fr_ca locale. The .js file should have something as below:

angular.module('locale', ['ngLocale']) : module definition with a dependency on the ngLocale module:

<!doctype html><html ng-app="locale"><head><meta charset="utf-8"><script src="lib/angular/angular.js"></script><script src="lib/angular/angular-locale_fr-ca.js"></script><script src="locale.js"></script></head><body ng-controller="LocaleCtrl">...</body>

Page 23: Introduction to Angular.JS

Related examples:{{now | date:'fullDate'}} will return full date based on the locale as set{{100 | currency:'€'}}{{1000.5 | number}}

Handling Translations: The text to be translated for different language.The primary idea is, you have to have JSON structure with key value pairs for different locales. You need to use the keys in places where you want the translations based on the user  locale.

Example:{'crud.user.remove.success': 'A user was removed successfully.','crud.user.remove.error': 'There was a problem removing a user.'. . .}

In your HTML, you can write something like below <span>Hello, {{name}}!</span> to <span>{{'greetings.hello' | i18n}}, {{name}}!</span> You do understand that you need the JSON for the locale with the key greetings.hello ----

Page 24: Introduction to Angular.JS

Building Your Own Directives Directives can appear as HTML elements,

attributes, comments, or CSS classes. Examples

<my-directive></my-directive><input my-directive><!-- directive: my-directive--><input>

Defining a Directive angular.module('app', []).directive('myDir',

function() {return myDirectiveDefinition;

});

Page 25: Introduction to Angular.JS

Writing a Button Directive

describe('button directive', function () {var $compile, $rootScope;beforeEach(module('directives.button'));beforeEach(inject(function(_$compile_, _$rootScope_) {$compile = _$compile_;$rootScope = _$rootScope_;}));

it('adds a "btn" class to the button element', function() {var element = $compile('<button></button>')

($rootScope);expect(element.hasClass('btn')).toBe(true);});

});});

Page 26: Introduction to Angular.JS

Using the button directive

<button type="submit">Click Me!</button>

Implementing a Custom Validation Directives Now we have our tests in place, so we can implement the

functionality of the directive: myModule.directive('validateEquals', function() {

return {require: 'ngModel',link: function(scope, elm, attrs, ngModelCtrl) {function validateEqual(myValue) {

var valid= (myValue === scope.$eval(attrs.validateEquals));

ngModelCtrl.$setValidity('equal', valid);return valid ? myValue : undefined;

}

Page 27: Introduction to Angular.JS

ngModelCtrl.$parsers.push(validateEqual);ngModelCtrl.$formatters.push(validateEqual);

scope.$watch(attrs.validateEquals, function() {

ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);

});}};

});

Page 28: Introduction to Angular.JS

Plunker http://plnkr.co/

Batarang

Page 29: Introduction to Angular.JS

http://todomvc.com/ http://karma-runner.github.io/ https://github.com/vojtajina/testacular/ Bindonce