Getting Started with AngularJS


Published on

My presentation from SDP 2013

Published in: Technology, Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Dependency Injection ( ($injector ($injector)
  • Scope API reference ($rootScope.Scope)Use $watch to register a callback to be executed when an expression changesUse $apply to execute an expression in angular
  • Different kinds of services ( great explanation of the different kinds and when to use them (!msg/angular/56sdORWEoqg/b8hdPskxZXsJ)The $provide service ($provide#methods_value)
  • - The $http service ($http)
  • - The $resource Service ($resource)
  • Forms Guide ( directive ( (
  • - ngModelController (
  • Routing tutorial ($routeProvider ($routeProvider)$routeParams ($routeParams)ngView ($location ($location)$locationProvider ($locationProvider)How to use the $location service ($location)HTML5 History API (
  • Getting Started with AngularJS

    1. 1. SELA DEVELOPER PRACTICE December 15-19, 2013 Moshe Levi Senior Consultant, SELA Blog : Twitter : @levimos Getting Started With AngularJS © Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel |
    2. 2. Agenda Introduction Modules and Dependency Injection Controllers and Scope Services Filters Form Validation Directives Routing
    3. 3. The Modern Web From web pages to web applications More and more logic is pushed to the client
    4. 4. The Problem As we add more and more JavaScript, our application is getting: Hard to Understand Hard to Test Hard to Maintain
    5. 5. What is AngularJS? An MVC framework for developing CRUD style web applications Developed by Google Works on all modern web browsers Open source (MIT license) Very opinionated
    6. 6. Building Blocks Module Module Module Two-Way Binding Template Scope Controller Service Routing Filter Directive Dependency Injection
    7. 7. Hello Angular <!doctype html> <html> <head> <title>Hello Angular</title> <script src="angular.js"></script> </head> <body ng-app> <input type="text" ng-model="name" placeholder="Enter Your Name"/> <p>{{name}}</p> </body> </html>
    8. 8. Angular Application Flow The browser makes an HTTP request to the server to load the initial template and scripts Angular loads and waits for the page to be fully loaded. Then, it searches for the ng-app directive and loads the associated module and its dependencies Angular compiles the template, adds listeners on DOM elements and evaluates bindings From now on – Angular is in charge
    9. 9. Modules Divides the application into small, reusable, self contained components Defined with the angular.module function Each module has a unique name Can be dependent on other modules Inside of a module, you can create Services Controllers Filters Directives
    10. 10. Dependency Injection Each angular application has an $injector All of angular’s building blocks are created by the $injector Components are injected by parameter name matching Functions need to be annotated Automatic inference – fails for minified code $inject property Inline array
    11. 11. Using the $injector angular.module('myModule', []) .factory('serviceA', ['$log', function($log) { return { do: function(message) { $'Inside A ' + message); } }; }]) .factory('serviceB', ['serviceA', function(serviceA){ return { do : function() {'Gretting from B'); } }; }]) .run(function($injector) { var serviceB = $injector.get('serviceB');; });
    12. 12. $scope The glue between the controller and the view The context for evaluating expressions Each application has a single $rootScope Each controller has its own scope Scopes are hierarchical
    13. 13. Controllers Contains the business logic for the view Sets up the initial state of the $scope Adds behavior to the $scope Associated with a DOM element with the ngcontroller directive
    14. 14. Creating a Controller Like anything else, controllers are created inside of a module The $scope is injected automatically var myModule = angular.module('myModule', []); myModule.controller('myController', function($scope){ $scope.tasks = []; $scope.addTask = function (task) { $scope.tasks.push(task); }; $scope.deleteTask = function (index) { $scope.tasks.splice(index, 1); }; });
    15. 15. Scope, Controllers, and Modules Demo
    16. 16. Services Reusable singleton objects that carry out a specific task Can be injected into controllers, filters, directives, or other services Created only when needed There are many built-in services for common tasks Use the $provide service or the module’s helper methods to create your own services
    17. 17. Built-In Services $log $rootScope $http $q $window $rootElement $location $parse $resource $timeout $cacheFactory $animate $compile $interval
    18. 18. Registering and Using Services var myModule = angular.module('myModule', []); myModule.factory('myFactory', function() { return 'Hello World'; }); myModule.controller('myController', function ($scope, myFactory) { // Value is 'Hello Moshe' $scope.myFactory = myFactory; });
    19. 19. Registering and Using Services Demo
    20. 20. The $http Service Used for communication with remote HTTP servers Basically, an XHR wrapped as an angular service Supports transformation of requests and responses Automatically serialized and deserializes JSON Supports interception of requests and responses Can be used for cross application concerns like authentication, error handling, and logging
    21. 21. Using The $http Service // You can use one of the six shortcut functions $http.get('/api/questions') .success(function(data, status, headers, config) { // Called on success }) .error(function(data, status, headers, config) { // Called on error }); $'/api/questions', question).success(…).error(…); $http.put(('/api/questions', question).success(…).error(…); $http.delete('/api/questions/1').success(…).error(…); $http.head('/api/questions').success(…).error(…); $http.jsonp(‘question?callback=callback').success(…).error(…); // Or invoke it as a function and provide a config object $http({})
    22. 22. The $resource Service Used for interaction with RESTful web services An abstraction on top of the $http service Requires dependency on the ngResource module and inclusion of angular-resource.js All the default HTTP verbs except PUT are configured by default Custom actions can be configured Returns an object with convenient methods for interaction with a RESTful web service (get, query, $save, $remove, …)
    23. 23. Using The $resource Service angular.module('resourceDemo', ['ngResource']) .controller('questionsCtrl', function ($scope) { var Question = $resource('/api/v1.0/questions/:id', {id: '@id'}); $scope.loadQuestions = function () { $scope.questions = Question.query(); }; $scope.removeQuestion = function(question){ question.$remove(); }; });
    24. 24. Core Services Demo
    25. 25. Filters Formats the value of an expression for display to the user {{ expression | filter }} May have arguments {{ price | number:2}} Filters are chainable You can create your own filters and register them using the $filterProvider service or the module’s filter method Many built in filters such as currency, date, number, uppercase, lowercase, filter, orderBy, and more
    26. 26. Creating Custom Filters var myModule = angular.module('myModule', []); myModule.filter('uppercase', function() { return function (text) { return (text || "").toUpperCase(); }; }); myModule.filter('reverse', function() { return function (text) { return (text || "").split("").reverse().join(""); }; });
    27. 27. Filters Demo
    28. 28. Forms Each form directive creates an instance of FormController Aggregates the state of all its controls Sets CSS classes according the state (ng-valid, ng-invalid, ng-pristine, ng-dirty) Available to the current scope by its name Use the ng-submit or ng-click directives to specify the method to call when the form is submitted
    29. 29. ng-model Each ng-model directive creates an instance of NgModelController Provides a two way data binding Provides automatic validation for most common HTML5 input types Tracks the controls state Sets CSS classes according to the state (ng-valid, nginvalid, ng-pristine, ng-dirty) Validation errors are exposed via the $error property Angular provides additional validation directives (required, minlength, maxlength, …)
    30. 30. Using Forms <form name="form" novalidate> <div> <input type="text" name="title" ng-model="question.title" required /> <div ng-show="form.title.$dirty && form.title.$invalid"> <span ng-show="form.title.$error.required"> Title is mandatory </span> </div> </div> <div> <textarea name="content" rows="10" ng-model="question.content" required> </textarea> <div ng-show="form.content.$dirty && form.content.$invalid"> <span ng-show="form.content.$error.required"> Content is mandatory </span> </div> </div> <button ng-click="addQuestion(question)" ng-disabled="form.$invalid"> Submit </button> </form>
    31. 31. Forms Demo
    32. 32. Directives Most of the things we’ve seen so far are built in directives (ng-app, ng-controller, ng-repeat, ngmodel, required, …) Allows you to extend the existing HTML vocabulary Create new elements Add new behavior to existing element Registered via the modules directive method
    33. 33. Creating a Custom Directive The directive method receives a function that returns an object with the following properties: restrict – Whether the directive can be used as an element (E), attribute(A), class(C), or comment(M) template templateUrl – The DOM content scope – An isolated scope for reusability, otherwise, the directive receives its parent’s scope Properties can be bound to the parent scope by prefixing them with the =, @, and & symbols
    34. 34. Creating a Custom Directive link – A function that is called during the linking phase and can be used to manipulate the element or register event handlers transclude – Whether child element should be included in the template (using ng-transclude) require – Specifying a dependency on other directive Prefix with ^ to look for the directive on parent elements The default is the same element controller – Is used to expose an API to other directives
    35. 35. Creating a Custom Directive myModule.directive('question', function(){ return { restrict: 'E', scope: { title: '=', content: '=', remove: '&' }, template: "<h1>{{title}}</h1><p>{{content}}</p><button ng-click='remove()'>Remove</button>" }; }); <div ng-repeat="q in questions"> <question title="qestion.title" content="question.content" remove="remove(question)"/> </div>
    36. 36. Directives Demo
    37. 37. Routing Use $routeProvider to register routes Requires a dependency on the ngRoute module and inclusion of angular-route.js Register new routes with when(path, route) The path can be parameterized Parameters will be accessible through $routeParams Route object should contain template templateUrl – The HTML to render controller – The controller to associate with the template resolve – Optional promises to resolve before rendering Template is rendered inside ng-view Register a fallback route with otherwise
    38. 38. Registering Routes angular.module('heapOverflowApp', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider. when('/questions', { templateUrl: '/partials/questions', controller: "QuestionsCtrl“ }) .when('/questions/:id', { templateUrl: '/partials/question', controller: "QuestionCtrl“ }) .otherwise({redirectTo: '/questions'}); }]);
    39. 39. Routing Demo
    40. 40. Resources The Demo Official documentation
    41. 41. Summary Modules and Dependency Injection Controllers and Scope Services and Filters Form Validation Directives Routing Email :
    42. 42. Questions