Angularjs
Upcoming SlideShare
Loading in...5
×
 

Angularjs

on

  • 2,243 views

 

Statistics

Views

Total Views
2,243
Views on SlideShare
2,243
Embed Views
0

Actions

Likes
4
Downloads
95
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Angularjs Angularjs Presentation Transcript

  • ANGULAR JS Getting Started Guide
  • Agenda • Welcome To Angular • Traditional “Hello World” Example • Angular Concepts • Filters • Directives • Multiple Views and Routes
  • Meet Angular • Started on 2009 by google engineers Miško Hevery and Brad Green • Complete client-side solution for SPA
  • Reasons To Use Angular • Technological and methodological solution to SPA • Best practices out-of-the-box • Active community effort
  • Reasons To Reconsider • Still no big apps written in angular • Adapting existing code takes work
  • A Traditional Hello World • Demo: A first angular program • Code: 
 http://jsbin.com/UkIhono/1/edit?html,js,output
  • What We Learned • An angular app has a root DOM node, marked by ng-app <html ng-app="MyApp">
  • What We Learned • We can use {{ … }} to inject JavaScript data into our DOM • Values are searched in the active scope <div ng-controller="Hello"> <h1>{{text}}</h1> </div>
  • What We Learned • Controllers are JS objects • They are used to assign values to the active scope <div ng-controller="Hello"> <h1>{{text}}</h1> </div>
  • What We Learned • Some HTML elements got special attributes called directives. • We met: ng-app, ng-controller • Directives tell angular how to process the page
  • What We Learned • We registered a controller factory using a special angular function. • Angular later creates the controller instance myApp.controller('Hello', ['$scope', function($scope) { $scope.text = 'Welcome To Angular'; }]);
  • What We Learned • When registering a controller, we also tell angular what services it needs • In our example, we asked for $scope
  • Angular MVC Data (Model) DOM (View) 'Welcome To Angular' <h1>Welcome To Angular</h1> Controller JS Code
  • Q&A
  • Lab • Implement an Angular app displaying: • • 3 Input box for quantities • 1 push button titled “Calculate total” • • 3 product name 1 result input bux Display quantity values stored in JS code
  • Angular Concepts • Client side templates • MVC architecture • Data binding • State and transitions • Object lifecycle
  • Client Side Templates <h1>{{text}}</h1> + $scope.text = 'Welcome To Angular'; <h1>Welcome To Angular</h1>
  • Client Side Templates • No need to access server for rendering • Decouple view from JS code
  • Data Binding (before angular) var newValue = 'bob is happy'; $('input').val(newValue); <input /> $('input').on('input', function() { self.value = $(this).val(); });
  • Data Binding (before angular) • JS code is coupled with HTML • Too much code
  • Data Binding (with angular) $scope.tagline = 'Bob is happy today'; <input /> function get_tagline() { return $scope.tagline; }
  • Data Binding (with angular) • Decouple JS code from HTML • Less code
  • Q&A
  • Data Binding
  • Bind Event Handlers • Angular assigns event handler from HTML using directives • Example: Add functionality to calculate_total() button from previous lab
  • Bind Event Handlers • But: There’s a bug … • Data is not updated back (from DOM to JS) • Let’s solve using angular
  • DOM -> JS <input type="text" ng-model="hats.units" />
  • ng-model • Binds input value to a $scope property • When either changes, update the other one
  • Other Available Bindings • ng-bind: binds text contents of an element • ng-bind-html: binds innerHTML of an element
  • Demo • Let’s write a small angular app with 3 text areas • Text in all 3 textareas should always be the same
  • Q&A
  • Lab • Fix previous lab so button will calculate the correct items quantity • Add a price to every item, and display price as well
  • Angular Filters
  • Currency Problem • Normal numbers can have strange values • 8613871$ • 2387.182617187351$ • That’s hard to read as a currency
  • Currency Problem • What would you do ?
  • Currency Problem • We could try to write a to_currency() function • Use it every time we assign a value
  • Currency Problem • Or, we could just say … <span class="price">{{ price | currency }}</span>
  • Angular Filters • A pipe in an expression tells angular to run it through a filter before displaying • A filter is just a function taking input and returning an output (can also take parameters)
  • Angular Filters • What you get: • Clear display code • General reusable functions
  • Built-In Filters • json • date • limitTo • orderBy • lowecase • uppercase • number <span class=“price"> {{ price | currency }} </span> ! <span class=“name"> {{ firstname | uppercase }} </span> ! <span class=“date"> {{1288323623006 | date:’medium'}} </span>
  • Custom Filters 1. app.filter('longest', function() { 2.   return function(input) { 3.   4.     if ( input.length == 0 ) return ''; 5.   6.     var result = input[0]; 7.     for ( var i=1; i < input.length; i++ ) { 8.       if ( input[i].length > result.length ) result = input[i]; 9.     } 10.   return result; 11. } 12.});
  • Q&A
  • Directives <button ng-click="count = count + 1" ng-init="count=0">   Increment </button> ! count: {{count}}
  • Angular Directives • A directive “tells” angular compiler what to do with the node
  • Using Directives <!-- 1: as an attribute declaration --> <a custom-button>Click me</a>   <!-- 2: as a custom element --> <custom-button>Click me</custom-button>   <!-- 3: as a class (used for old IE compat) --> <a class="custom-button">Click me</a>   <!-- 4: as a comment --> <!-- directive: custom-button -->
  • Let’s start with ng-repeat • Takes an array of values • Repeats an element for each item in the array • Useful for writing lists
  • Let’s start with ng-repeat <ul>   <li ng-repeat="person in people”> Name: {{person.name}} </li> </ul>
  • But there’s more • $index translates to the index of current iteration • $first is true on the first iteration • $last it true on the last iteration • $middle is true in the middle • $even and $odd are true on even and odd 
 iterations respectably
  • Repeat + Filters = Win I have {{friends.length}} friends. They are: <input type="search" ng-model="q" placeholder="filter friends..." /> ! <ul class="example-animate-container">   <li class="animate-repeat" ng-repeat="friend in friends | filter:q">     [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.   </li> </ul> http://docs.angularjs.org/api/ng.directive:ngRepeat
  • Other Directives • Directive Categories: • Handling events • Flow control in DOM creation • Specific solutions • Custom directives
  • Event Handlers ng-click ng-copy ng-mousedown ng-change ng-paste ng-mouseup ng-blur ng-cut ng-keypress ng-focus hg-submit ng-mouseover ng-dblclick ng-mouseenter
  • Conditional DOM • ng-if • ng-switch • ng-hide • ng-show • ng-readonly • ng-repeat <button ng-click="count = count + 1"        ng-init="count = 0">Clicks: {{count}} </button>     <p ng-hide="count%3 == 0">{{ welcome_text }}</p>
  • Other Directives • ng-class • ng-cloak • ng-href • ng-src • ng-style
  • Q&A
  • Lab • Modify our previous Shopping Cart page to allow flexible products • Controller should keep a list of products • Page should display products from the list
  • Routes and Views Products List Page Shopping Cart Page viewport Item Details Page
  • Routes and Views Products List Page viewport Shopping Cart Page Item Details Page Angular Router renders a template into the viewport
  • Routes and Views /products Products List Page viewport /cart Shopping Cart Page /item/72 Item Details Page Angular Router renders a template into the viewport
  • Router Demo myApp.config(['$routeProvider', '$locationProvider', function($routes, $location) {   $routes.     when('/', {       templateUrl: '/app/src/views/list.html',       controller: 'ProductsList'     })     .when('/item/:id', {       templateUrl: '/app/src/views/details.html',       controller: 'ProductDetails'     })     .otherwise({       redirectTo: '/'     });     $location.html5Mode(true); }]);
  • Router Notes • html5Mode controls whether to use # • Beware of relative paths
  • Router Events • When using a router, you get the following events on the $rootScope • $routeChangeSuccess • $routeChangeError
  • Handling Route Events • Following code shows an alert after each page transition • Can use from any Controller $scope.$on('$routeChangeSuccess', function() {   alert('wow'); });
  • Demo • Write a message list two pages application • Page 1: list all messages • Page 2: message details (on specific message) • Clicking a message leads to page 2
  • Q&A
  • Lab • Add Breadcrumbs controller to the example • Should create a list of past visited pages (names + links)
  • Client Server Communication Getting data from server ! Using RESTful resources
  • The Basics • $httpProvider is a wrapper around XHR • It uses promises for its API magic
  • Given The User List Code <div ng-controller="users">
 <ul>
 <li ng-repeat="u in users">
 <a>{{u.name}}</a>
 </li>
 </ul>
 </div> app.controller('users', ['$scope', function($scope) {
 $scope.users = [
 { name: 'bob' },
 { name: 'john' },
 { name: 'brad' }
 ];
 }]);

  • Getting Data From Server app.controller('users', ['$scope', '$http', function($scope, $http) {
 $http.get('/users.json')
 .success(function(data, status) {
 $scope.users = data;
 });
 }]);
  • $http API • $http(config) • $http.get(url, config) • $http.post(url, data, config) • $http.put(url, data, config) • $http.delete(url, config)
  • $http config $http({
 method: 'GET',
 url: '/users.json',
 params: { sort: 'asc' },
 headers: { 'my-header' : 'header-value' },
 cache: true,
 timeout: 3000 // milliseconds
 });

  • Other Chaining Operations • .success(function(data, status, headers, config) { } ) • .error(function(data, status, headers, config) { } )
  • $http • Low level wrapper around XHR • Simple to use and understand
  • Demo • Let’s use $http to communicate with REST API • Display a list of colours • Clicking a colour -> Delete • Provide a form to add a new colour
  • Meet ngResource $save POST /colors $delete DELETE /colors/7 $query GET /colors $get GET /colors/7 Color
  • Using ngResource var app = angular.module('MyApp', ['ngResource']);
  • Using ngResource 
 
 app.controller('users', ['$scope', '$resource', function($scope, $resource) {
 
 var Color = $resource('/colors/:id');
 
 $scope.colors = Color.query();
 
 }]);

  • Using ngResource 
 app.controller('users', ['$scope', '$resource', function($scope, $resource) {
 
 $scope.remove = function(id) { $scope.colors[id].$remove({id: id}, function() {
 $scope.colors.splice(id, 1);
 });
 
 };
 
 }]);

  • ngResource • High level API for communicating with REST APIs • Cleaner and less callbacks
  • Q&A
  • Angular + jQM ! Introducing angular-jqm ! Concepts ! Demos !
  • Meet angular-jqm • Native angular directives for JQM • Github:
 https://github.com/angular-widgets/angular-jqm • Docs:
 http://angular-widgets.github.io/angular-jqm/master/ docs/#/api
  • Concepts • jQM turns normal HTML to mobile-friendly markup • angular-jqm is a full reimplementation of the transformation (without jQuery or jQM dependencies) • Uses same CSS
  • Concepts <div data-role="header">
 <h1>Page Title</h1>
 </div> <div jqm-header>
 <h1>Welcome To ng-jqm</h1>
 </div> <div role="banner" class="ui-header ui-bar-a" data-role="header">
 <h1 aria-level="1" role="heading" class="ui-title">Page Title</h1>
 </div>

  • Advantages • Uses angular style • No “dirty” hacks
  • Disadvantages • Need to reimplement entire transformation code • (Still) Not feature-complete
  • angular-jqm boilerplate <!DOCTYPE html>
 <html >
 <head>
 <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"/>
 
 <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
 <script src="angular.js"></script>
 <script src="angular-mobile.js"></script>
 <script src="angular-jqm.js"></script>
 <!-- include your application script files here -->
 <script src="app.js"></script>
 </head>
 
 <body ng-app="app">
 
 
 <div jqm-caching-view></div>
 </body>
 
 
 </html>
  • angular-jqm boilerplate var mod = angular.module('app', ['jqm']);
 mod.config(function($routeProvider) {
 // A route for a single page
 $routeProvider.when("/", {
 redirectTo: "main.html"
 });
 // A route for all pages in one folder
 $routeProvider.when("/:page", {
 animation: 'page-slide',
 templateUrl: function(params) {
 return params.page;
 }
 });
 });
  • Lab • Write an angular-jqm app to show a list of items and quantities • Clicking a list item increases its quantity
  • Q&A
  • Thanks For Listening • Ynon Perek • ynon@ynonperek.com • http://ynonperek.com
  • Photos From • http://placeit.net • http://123rf.com