Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

Angular Js Get Started - Complete Course

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Wird geladen in …3
×

Hier ansehen

1 von 146 Anzeige

Angular Js Get Started - Complete Course

Herunterladen, um offline zu lesen

Angular Js Advantages.Developed by Google - Most Popular, SPA (Single Page Appplications), Data Binding, Easy to Test.
Complete guide for Angular Js. Covers Basics of Angular - Module, Controllers, Filters, and Advanced topics Routing, Services, UI-Routing

Angular Js Advantages.Developed by Google - Most Popular, SPA (Single Page Appplications), Data Binding, Easy to Test.
Complete guide for Angular Js. Covers Basics of Angular - Module, Controllers, Filters, and Advanced topics Routing, Services, UI-Routing

Anzeige
Anzeige

Weitere Verwandte Inhalte

Diashows für Sie (20)

Ähnlich wie Angular Js Get Started - Complete Course (20)

Anzeige

Aktuellste (20)

Anzeige

Angular Js Get Started - Complete Course

  1. 1. ANGULAR JS GET STARTED By, Santha Mani
  2. 2. INTRODUCTION Angular JS is a JavaScript framework you can use to build applications, but run in a web browser using HTML. The Angular JS framework started as a project inside of Google, but it's now an open source project so anyone can contribute to Angular or use Angular in their own applications.
  3. 3. BENEFITS Used for Single page and line of pages of application Dependency Injection Two-way binding Testing MVC Controlling the DOM elements like Directives, Filters, Services, Controllers,…
  4. 4. ANGULARJS.ORG – HOME FOR ANGULAR angularjs.org - this is where you can find links to mailing lists, find the documentation, find a Download button if you want to bring all of the Angular libraries down and use them locally, and there's also a link to GitHub where the raw source code lives. A related website you might be interested in is, builtwith.angularjs.org. This website includes pictures and links to other public websites that have been built with AngularJS.
  5. 5. AN ANGULAR APPLICATION There are only two requirements for adding Angular JS to a web page <script> tag pointing to angular.js. need to add an ng-app attribute somewhere in your HTML ng-app, in Angular terminology, is called a directive, and it is just one of many directives that Angular provides. The ng prefix is short for Angular.
  6. 6. EXAMPLE
  7. 7. EXAMPLE Angular found that particular binding expression, that's what we call it, and an output into the web page. The double curly braces are what some people would call mustaches or handlebars, they are binding expressions in Angular.  {{ expression }} – binding expression ng-init – initializes the application in the current scope.
  8. 8. <!DOCTYPE html> <html> <head> <title>Angular JS - Arrays(StringS)</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></scri pt> </head> <body> <div ng-app="" ng-init="program=['HML','CSS','Jquery','AngularJs']"> <div ng-app="" ng-init="number=[5,25,50,75,100]"> <p> This is fist program:<span ng-bind="program[3]"></span><br> This is last program:<span ng-bind="program[1]"></span> </p> <p>Single quotes to be mentioned for sring values in the array declaration</p> </div> </body> </html>
  9. 9. MODULE Modules are the basic building block of Angular. Everything exists inside of our module. A module is a container for different parts of your application i.e., controller, services, directives, filters etc.. Specifies the bootstrapping
  10. 10. SYNTAX var myApp = angular.module(“myModule”,[]); myModule = name of our Module Empty square braces [] = dependents of our module
  11. 11. EXAMPLE var myApp = angular.module('myModule', []); <!DOCTYPE html> <html ng-app = "myModule"> <head> <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"> </script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body > <h1>Hello Plunker!</h1> {{ 8/4}} </body> </html>
  12. 12. CONTROLLER The job of a controller is To build a model for View. It does by attaching to the $scope object. $scope is not a model it’s the data that we attach to $scope is the model.
  13. 13. CREATING A CONTROLLER ng-controller is an attribute that we place into our HTML, we can specify the name of a controller that we want to take control of some area of the HTML Angular will invoke the controller function when it needs to create a controller to manage an area of the webpage. $scope is a component provided by Angular. What we can do with the scope argument is assign our model to the object.
  14. 14. EXAMPLE var myApp = angular.module('myModule', []); myApp.controller('myController', function($scope) { $scope.message = "Hello Angular"; });
  15. 15. <!DOCTYPE html> <html ng-app="myModule"> <head> <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"> </script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body> <h1>Hello Plunker!</h1> {{ 8/4}} <br> <div ng-controller="myController"> {{message}} </div> </body> </html>
  16. 16. EXAMPLE Now we've seen a controller in action, and we see that the primary responsibility of a controller is to set up the model on our $scope object. Angular passes $scope to our controller function, and our controller manipulates that scope. It only manipulates $scope by attaching a model. And then we use binding expressions to move data from the $scope into the view.
  17. 17. EXAMPLE ///<refereence path="angular.min.js"/> var myApp=angular.module("myModule",[ ]); myApp.controller("myController", function($scope) { var employee = { firstName: "Avinash Kumar", lastName: "Gaddamanugu", gender: "Male“ }; $scope.employee=employee; });
  18. 18. <!DOCTYPE html> <html ng-app="myModule"> <head> <title>Complex ng-model</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angula r.min.js"></script> <script src="angular.js"></script> <script type="text/javascript" src="ComplexScripts.js"></script> </head> <body> <div ng-controller="myController"> <div> First Name: {{ employee.firstName }} </div> <div> Last Name: {{ employee.lastName }} </div> <div> Gender: {{ employee.gender }} </div> </div> </body> </html>
  19. 19. CAPABILITIES Multiple Controller Complex Controller Nested Controller
  20. 20. DIRECTIVES Controls the DOM elements (behavior) It is prefixed by ng. Eg: ng-init, ng-app, ng-model, ng-repeat The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
  21. 21. NG-SRC The purpose of the ng-source directive is that once Angular is up and running, once it has evaluated this expression, then it will come in and set the actual source attribute for that image and the image should be successfully downloaded and you'll avoid these 404 errors. So ng-source is just a directive to set the source of an image when there's a data binding expression involved.
  22. 22. TWO-WAY BINDING Keeps the model and the view sync all the time. Change in model updates the view and change in view updates the model. Model View Change in View updates View Change in View updates Model
  23. 23. NG-MODEL Bind the value of an input field to a variable created in Angular JS Ng-model - always keep your data in sync It can be apply to inputs, select and textarea Example Ng-model.html, ng-model.js Also can specify in complex way Complex Module & Controller.html & Complex ng- model.js
  24. 24. NG-MODEL CAN PROVIDE TYPE VALIDATION FOR APPLICATION DATA (NUMBER, E-MAIL, REQUIRED). <!DOCTYPE html > <html ng-app="" > <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js "></script> <body> <form name="myForm"> Email: <input type="email" name="myAddress" ng-model="text"> <span ng-show="myForm.myAddress.$error.email">Not a valid e- mail address</span> </form> <p>Enter your e-mail address in the input field. AngularJS will display an errormessage if the address is not an e-mail.</p> </body> </html>
  25. 25. NG-MODEL DIRECTIVE CAN PROVIDE STATUS FOR APPLICATION DATA (INVALID, DIRTY, TOUCHED, ERROR) <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'"> Email: <input type="email" name="myAddress" ng-model="myText" required> <p>Edit the e-mail address, and try to change the status.</p> <h1>Status</h1> <p>Valid: {{myForm.myAddress.$valid}} (if true, the value meets all criteria).</p> <p>Dirty: {{myForm.myAddress.$dirty}} (if true, the value has been changed).</p> <p>Touched: {{myForm.myAddress.$touched}} (if true, the field has been in focus).</p> </form> </body></html>
  26. 26. NG-MODEL DIRECTIVE PROVIDES CSS CLASSES FOR HTML ELEMENTS, DEPENDING ON THEIR STATUS ng-model directive adds/removes the following classes, according to the status of the form field ng-empty ng-not-empty ng-touched ng-untouched ng-valid ng-invalid ng-dirty ng-pending ng-pristine
  27. 27. NG-REPEAT Similar to foreach() loop in C#. Table format Ng-repeat.html & ng-repeat.js List Format Ul-ng-repeat.html & ul-ng-repeat.js
  28. 28. NG-OPTIONS Used for filling a dropdown list with options. Selected value to be an object For key-value pair Using an object as the data source, x represents the key, and y represents the value: <select ng-model="selectedCar" ng-options="x for (x, y) in cars"> </select> The selected value will always be the value in a key-value pair. The options in the dropdown list does not have to be the key in a key-value pair, it can also be the value, or a property of the value object <select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars"> </select>
  29. 29. NG-OPTIONS VS NG-REPEAT The ng-options directive was made especially for filling a dropdown list with options. The ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create options in a dropdown list. Dropdowns made with ng-options allows the selected value to be an object, while dropdowns made from ng-repeat has to be a string.
  30. 30. NG-OPTIONS VS NG-REPEAT <select ng-model="selectedCar"> <option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option> </select> <select ng-model="selectedCar" ng-options="x.model for x in cars"></select>
  31. 31. CUSTOM DIRECTIVES Create New Directives In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the .directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive. When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must use -separated name, w3-test-directive
  32. 32. EXAMPLE<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script> <body ng-app="myApp"> <w3-test-directive></w3-test-directive> <script> var app = angular.module("myApp", []); app.directive("w3TestDirective", function() { return { template : "<h1>Made by a directive!</h1>" }; }); </script> </body> </html>
  33. 33. CUSTOM DIRECTIVE You can invoke a directive by using: Element name <w3-test-directive></w3-test-directive> Attribute <div w3-test-directive></div> Class <div class="w3-test-directive"></div> Comment <!-- directive: w3-test-directive --> You must add the value "C" to the restrict property to be able to invoke the directive from a class name.
  34. 34. RESTRICTIONS Restrict your directives to only be invoked by some of the methods The legal restrict values are: E for Element name A for Attribute C for Class M for Comment By default the value is EA, meaning that both Element names and attribute names can invoke the directive.
  35. 35. EVENT HANDLING – NG-CLICK An expression that’s going to be a function call Example Events.html & events.js
  36. 36. In addition to these built-in directives, angular allows you to write custom directives. Custom directives to perform activities like drag-and-drop, or custom directives that can wrap bootstrap widgets, or media players, or wrappers for google maps.
  37. 37. FILTERS Used to transform data Can do 3 different things Format data Sort data Filter data Can be used with a binding expression or a directive. To apply a filter use pipe (|) character {{ expression | filter : parameter }}
  38. 38. DATE YYYY - 4 digit year – Ex: 1992 YY - 2 digit year –Ex: 1992:-92 MMMM – Full name (January – December) MMM – Jan – Dec MM – 01-12 M – Numerical Formats (1-12 ) (No leading zeros) dd – 01 -31 d – 1 – 31 (No leading zeros)
  39. 39. THE FILTER FILTER The Filter filter selects a subset of an array. The Filter filter can only be used on arrays, and it returns an array containing only the matching item.
  40. 40. LimitTo Filter limitTo filter: Can be used to limit the number of rows or characters in a string. {{ expression | limitTo : limit : begin }}
  41. 41. ADDING FILTERS TO DIRECTIVES Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter. <div ng-app="myApp" ng-controller="namesCtrl"> <ul> <li ng-repeat="x in names | orderBy:'country'"> {{ x.name + ', ' + x.country }} </li> </ul> </div>
  42. 42. SORTING ROWS IN A TABLE tablesorting.html tablesorting.js
  43. 43. SORTING BY MULTIPLE PROPERTIES Sortingdata.html Sortingdata.js Multiplesort.html Multiplesort.js
  44. 44. SEARCH MULTIPLE PROPERTIES Searchfilter.html Searchfilter.js
  45. 45. CUSTOM FILTERS Customfilter.html Customefilter.js
  46. 46. ng-hide & ng-show Used to control the visibility of the HTML element. Hide Salary: <input type="checkbox" name="checkbox" ng-model="hideSalary" /> <thead> <tr> <th>Name</th> <th>Gender</th> <th>City</th> <th ng-hide="hideSalary">Salary</th> </tr> </thead> <tbody> <tr ng-repeat="emp in employees"> <td> {{ emp.name }} </td> <td> {{ emp.gender }} </td> <td> {{ emp.city }} </td> <td ng-hide="hideSalary"> {{ emp.salary }} </td> </tr> </tbody>
  47. 47. ng-hide & ng-show <thead> <tr> <th>Name</th> <th>Gender</th> <th>City</th> <th ng-hide="hideSalary">Salary</th> <th ng-show="hideSalary">Salary</th> </tr> </thead> <tbody> <tr ng-repeat="emp in employees"> <td> {{ emp.name }} </td> <td> {{ emp.gender }} </td> <td> {{ emp.city }} </td> <td ng-hide="hideSalary"> {{ emp.salary }} </td> <th ng-show="hideSalary">####</th> </tr> </tbody>
  48. 48. ng-include Used to embed an HTML page into another HTML page. Used when we want specific view in multiple pages of our application The value of the ng-include can be The name of HTML page that to be reusable A property on the $scope object that points to the reusable HTML page.
  49. 49. SERVICE Is a an object that can be reused within an application. Eg: Math()- provides services to add number A service in angular is an object that provides some sort service that can be reused in a angular application. Angular JS has about 30 built-in services.
  50. 50. NEED OF SERVICE Single Responsibility Condition: States that an object should have a single responsibility. Services encapsulate reusable logic that doesn’t belong anywhere else (i.e., directives, filters, views, model & controller) Benefits Reusability Eg: $http Dependency Injection Testability
  51. 51. $location Service return information about the location of the current web page <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl"> <p>The url of this page is:</p> <h3>{{myUrl}}</h3> </div> <p>This example uses the built-in $location service to get the absolute url of the page.</p> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $location) { $scope.myUrl = $location.absUrl(); }); </script>
  52. 52. $interval Service <body> <div ng-app="myApp" ng-controller="myCtrl"> <p>The time is:</p> <h1>{{theTime}}</h1> </div> <p>The $interval service runs a function every specified millisecond.</p> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $interval) { $scope.theTime = new Date().toLocaleTimeString(); $interval(function () { $scope.theTime = new Date().toLocaleTimeString(); }, 1000); }); </script> </body>
  53. 53. $timeout Service <body> <div ng-app="myApp" ng-controller="myCtrl"> <p>This header will change after two seconds:</p> <h1>{{myHeader}}</h1> </div> <p>The $timeout service runs a function after a sepecified number of milliseconds.</p> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $timeout) { $scope.myHeader = "Hello World!"; $timeout(function () { $scope.myHeader = "How are you today?";}, 2000); }); </script>
  54. 54. $http Service <div ng-app="myApp" ng-controller="empController"> <table> <tr><th>Name</th></tr> <tr ng-repeat=“emp in empployees”> <td>{{emp.name}}</td> </tr> </table> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http ,$log) { $http.get(“data.json)then(function (response) { $scope.employees = response.data; }); }); </script>
  55. 55. PROMISE OBJECT $http service returns a promise object as the functions are executed asynchronously. A promise object is an object that promises to give you some result in the future, and that result might be the data that you need, or the result might be an error if the server was unavailable. The way I find out is to call a then() method on my promise and pass the then() method a function that will be called in the future.
  56. 56. EG: PROMISE OBJECT var myApp=angular.module(“serviceApp”,[]) .controller(“serviceCtrl”,function($scope, $http){ $http.get(‘sample.html’) .then(function(scope) { $scope.myWelcome = response.data; }); }); Function is called when the request completed successfully, we get response from the server Ex: http://andyshora.com/promises-angularjs-explained-as-cartoon.html
  57. 57. CUSTOM SERVICES An AngularJS service can be created or registered or created in four different ways, Using the service() method Using the factory() method Using the provider() method Using the value() method Using the constant() method
  58. 58. service() vs factory() Using the service() method uses the function constructor and it returns the object or instance of the function to work with. Using the factory() method uses the returned value of the function. It returns the value of the function returned after the execution
  59. 59. NORMAL SERVICE var myApp = angular.module("myModule", []) .controller("myController", function($scope){ $scope.transformString = function(input){ if(!input) { return input; } var output = ""; for (var i = 0; i < input.length; i++) { if(i>0 && input[i] == input[i].toUpperCase()) { output = output + " "; } output = output + input[i]; } $scope.output = output; } });
  60. 60. NORMAL SERVICE CALL In this we have two problems The controller code become complex and large If we want to reuse this code in any controller we have to duplicate that code within that controller. At the moment we start duplicating the maintainability of the application will be loss. To overcome this we encapsulate the service and inject that service into any controller where we want to use.
  61. 61. SERVICE/FACTORY METHOD It is used for creating the custom service and register this with angular. myApp.factory(‘stringService’, function(){ return { processingString: function(input){ ------ ---- } }; )}
  62. 62. SYNTAX var myApp = angular.module(“myModule”,[]) .controller(“myCtrl”,function($scope, stringService) { $scope.transformString = function(input) { $scope.out = stringService.processingString(input); } });
  63. 63. $http get() In Angularjs get ($http.get()) service or method is used to get data from remote HTTP servers. var app = angular.module('getserviceApp', []); app.controller('getserviceCtrl', function ($scope, $http) { // Simple GET request example: $http({ method: 'GET', url: '/sampleUrl', data: 'parameters' }) .then(function success(response) { // this function will be called when the request is success }, function error(response) { // this function will be called when the request returned error status }); });
  64. 64. SYNTAX method - This property is used to define required operator like get or send data. In angularjs we have different methods available. url - We need to send url of http server to perform required operations. data - If we have any parameters to send and get data from request url we will pass it using this parameter. then - In then property we will do our coding based on response status either success or failure. If it is success it will execute first method or in case if we get error second method will execute.
  65. 65. $http.get Properties config - The configuration object is used to generate the request. data - It’s string or an object which is used to carry response from the server. headers - This function is used to get header information. status - This property is used to get HTTP status code of the response. statusText - This property is used to get HTTP status text of the response.
  66. 66. $http post() method The $http.POST() services are used to send the data to a specific URL and expects the resource at that URL to handle the request that means we can say that POST method is used to Insert new data based on given URL
  67. 67. SYNTAX var app = angular.module('putserviceApp', []); app.controller('putserviceCtrl', function ($scope, $http) { // Simple Post request example: var url = 'posturl', data = 'parameters',config='contenttype'; $http.post(url, data, config) .then(function (response) { // This function handles success }, function (response) { // this function handles error }); });
  68. 68. $http.post() Properties config - The configuration object is used to generate the request. data - It’s either string or an object. headers - We can get header information. status - We can get HTTP status code of the response. statusText - Get HTTP status text of the response.
  69. 69. $http.put() method The $http.put() service in angularjs is used to upload a files to server and update existing data in server based on given URL. Generally $http.put method not allowed by many servers due to security reasons.
  70. 70. SYNTAX var app = angular.module('putserviceApp', []); app.controller('putserviceCtrl', function ($scope, $http) { // Simple Put request example: var url = 'puturl', data = 'parameters',config='contenttype'; $http.put(url, data, config).then(function (response) { // This function handles success }, function (response) { // this function handles error }); });
  71. 71. SYNTAX url - Used to send url of http server to perform required operations. data - This property to send required parameters to requested url. config - By using this property we can change content-type. After execution of our $http.put request we will get response based on that response status our success and failure methods will execut
  72. 72. $http put() Properties config - The configuration object is used to generate the request. data - It’s either string or an object. headers - We can get header information. status - We can get HTTP status code of the response. statusText - Get HTTP status text of the response.
  73. 73. $http.jsonp() Service In angularjs jsonp or json with padding service is used to make cross domain requests from client browser. By using $http.jsonp service in angularjs we can get data in json format and the server whatever we are requesting should support jsonp requests otherwise it’s worthless
  74. 74. BENEFIT Generally now a days browsers are blocking access data from a server which is in different domain due to same origin policy. By using angularjs $http.jsonp method we can access data from different domain without having any access problems.
  75. 75. SYNTAX var app = angular.module('jsonserviceApp', []); app.controller('jsonCtrl', function ($scope, $http) { //Call the service to get data in json var url = "Some API Url" + "?callback=JSON_CALLBACK"; $http.jsonp(url) .success(function (data, status, headers, config) { $scope.details = data; }) .error(function (data, status, headers, config) { $scope.statusval = status; }); });
  76. 76. JSON_CALLBACK “callback=JSON_CALLBACK” to url to make a service request. AngularJs is having its own callback pattern, so it will follow that pattern to handle jsonp callbacks. In angularjs always we need to send callback=JSON_CALLBACK with url while requesting jsonp service. Using this pattern we handle the JSONP call-back and its call-back is called JSON_CALLBACK.
  77. 77. Angularjs Success / Error Functions In angularjs while using $http services we have success() and error() functions with then property to display the success and failed response of request information. In angularjs we can use success and error methods with http GET, POST, PUT, DELETE, JSONP and PATCH services.
  78. 78. SYNTAX var app = angular.module('getserviceApp', []); app.controller('getserviceCtrl', function ($scope, $http) { // Simple GET request example: $http.get("url").then(function success(response) { // this function will be called when the request is success }, function error(response) { // this function will be called when the request returned error status }); });
  79. 79. anchorScroll Used to jump to specified element on the page. var myApp=angular.module("myModule",[ ]); myApp.controller("myController", function($scope, $location, $anchorScroll) { $scope.scrollTo = function(scrollLocation) //mention the id of the element { $location.hash(scrollLocation); $anchorScroll(); } });
  80. 80. CLIENT AND SERVER ROUTING Server-Side routing: A client would request a webpage or other resource from the server using a URL and the server retrieves the resource and sends it back to the client. Often this meant that an entire webpage would be sent back to the browser after each request to the server.
  81. 81. CLIENT – SIDE ROUTING Client – Side Routing However, when using a client-side framework like Angular, the requests to the server are of often for smaller bits of information rather than entire webpages and all of their related resources. Client-side routing doesn't replace server-side routing. All web applications still interact heavily with servers and those servers still need to accept a URL and use it to locate and return the resource needed by the client.
  82. 82. SERVER-SIDE ROUTING WITH SPAS AND CLIENT-SIDE ROUTING. SPA stands for Single Page Application. The idea behind a SPA is that it appears to the user as if it's one page in the browser and you only update portions of that page as the user interacts with the application.
  83. 83. ngRoute ngRoute is its own Angular module, and stored in its own JavaScript file. ngRoute module helps your application to become a Single Page Application. The ngRoute module routes your application to different pages without reloading the entire application.
  84. 84. WHAT DO I NEED To make your applications ready for routing, you must include the AngularJS Route module: <script src="https://ajax.googleapis.com/ajax/libs/angul arjs/1.4.8/angular-route.js"></script> Then you must add the ngRoute as a dependency in the application module:: var app = angular.module("myApp", ["ngRoute"]);
  85. 85. $routeProvider Define the $routeProvider using the config method of application. Work registered in the config method will be performed when the application is loading. ngRoute – provides the routing this our dependency $ routeProvider – used to configure routes
  86. 86. $routeProvider to configure routes app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.htm" }) .when("/red", { templateUrl : "red.htm" }) .when("/green", { templateUrl : "green.htm" }) .when("/blue", { templateUrl : "blue.htm" }); });
  87. 87. EXAMPLE var myApp=angular.module("myModule",["ngRoute"]) .config(function($routeProvider,$locationProvider) { $routeProvider .when("/",{ templateURL : "Template/home.html", controller : homeController; } });
  88. 88. WHERE DOES IT GO? Application needs a container to put the content provided by the routing. This container is the ng-view directive. There are three different ways to include the ng- view directive in your application <div ng-view></div> as attribute <ng-view></ng-view> as tag <div class="ng-view"></div> as class
  89. 89. USING CONTROLLERS With the $routeProvider you can also define a controller for each "view". var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.htm" }) .when("/london", { templateUrl : "london.htm", controller : "londonCtrl" }) .when("/paris", { templateUrl : "paris.htm", controller : "parisCtrl" }); }); app.controller("londonCtrl", function ($scope) { $scope.msg = "I love London"; }); app.controller("parisCtrl", function ($scope) { $scope.msg = "I love Paris"; });
  90. 90. otherwise() otherwise method, is the default route when none of the others get a match If you try to navigate to route that is not configured, any partial template will not be injected because angular doesn’t know the route of template/site. .otherwise({ redierctTo : “/main”; })
  91. 91. INLINE TEMPLATE The template property, allows you to write HTML directly in the property value, and not refer to a page. Eg: var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/", { template : "<h1>Main</h1><p>Click on the links to change this content</p>" }); })
  92. 92. $route Service It has two methods, reload and updateParams The updateParams method allows you to reload the current URL with a new set of route parameters. You pass the new parameters as properties on an object to the updateParams method. The property names that match parameter names you've configured on the route, will then have the new values inserted into the URL. The reload method will reload the current route. This will simply reload the current route within your Angular app, which mean it will make any necessary network calls, process route parameters, and generally treat the route as if you were visiting it for the first time.
  93. 93. $route Service - Parameters The current property : gives you a reference to the current route definition and allows you to exam the controller for the route, scope, and other variables used when creating the route's controller. The routes property : is an object containing all of the route definitions for your application. You can use it to see all of the routes you've configured on the route provider.
  94. 94. reload() By using the reload() function on the route service give us the ability to refresh the data on the home page of the app. .controller(“homeController, function($http,$route) var vm = this; vm. reloadData = function() { route.reloadData(); }
  95. 95. Route change This is used when we are filling long form application. This is created with a alert window asking for OK and Cancel OK: navigate to next partial template/page Cancel: stays in current page
  96. 96. Route Change When a route change occurs, then two events are generated $routeChangeStart $locationChangeStart The only difference between two events is the ‘next’ and ‘current’ parameters. The $locationChangeStart event ‘next’ and ‘current’ parameters has got complete next and current URL’s
  97. 97. $routechangestart() .controller(“studentController”, function($http,$scope,$route) $route.$on(“$routeChangeStart”, function(event,next,current) { if(!confirm(“Are you sure to navigate”)) { event.preventDefault(); } }
  98. 98. NAVIGATION PAGE We can also specify to which page we are navigating. .controller(“studentController”, function($http,$scope,$route) $route.$on(“$routeChangeStart”, function(event,next,current) { if(!confirm(“Are you sure to navigate” + next.$$route.orginalPath)) { event.preventDefault(); } }
  99. 99. $locationchangestart() .controller(“studentController”, function($http,$scope,$route) $route.$on(“$locationChangeStart”, function(event,next,current) { if(!confirm(“Are you sure to navigate”)) { event.preventDefault(); } }
  100. 100. NAVIGATION PAGE We can also specify to which page we are navigating. .controller(“studentController”,function($http,$scope,$route) $route.$on(“$locationChangeStart”, function(event,next,current) { if(!confirm(“Are you sure to navigate” + next)) { event.preventDefault(); } }
  101. 101. ROUTE RESOLVE If the components of the application i.e., database server, application and the client present in different machines and a network latency then the data few seconds to load. If the components of the application are in local machine, then there will not be any network latency.
  102. 102. REMOVE (#) SYMBOL Enable html5mode $locationProvider.html5mode(true); Remove # in anchor tag Include URL rewrite rule in web.config Set base href element to the location of single page application <base href=“/” /> all the partial templates are present within the root element
  103. 103. ANGULAR CASE-INSENSITIVE By default Angular is case sensitive To make a route to case insensitive make it true. $routeProvider.caseInsensitiveMatch = true;
  104. 104. CONTROLLER AS SYNTAX There is another mechanism to make the members of the controller available in the view i.e., Controller As Syntax With this there is no need for injecting the $scope object. Instead we use ‘this’ keyword.
  105. 105. <!DOCTYPE html> <html ng-app = “myModule”> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.m in.js"> </script> <script> var app = angular .module (“myModule”,[]) .controller (“myController”, function(){ this.message = “Angular JS Tutorial”; }); </script> <body ng-controller = “myController as myCtrl”> <h2> {{ myCtrl.message }} </h2> </body> </html>
  106. 106. NESTED CONTROLLER <div ng-controller="countryController"> {{name}} <div ng-controller="stateController"> {{name}} <div ng-controller="cityController"> {name}} </div </div> </div>
  107. 107. CONTROLLER vs SCOPE Controller as syntax is new & released 1.2.0 officially. $scope is the old technique & is available since the initial version of angular is released. Controller as syntax makes code more readable. If you want to use $scope object it is to be injected into the controller function, where as with controller as syntax there is no need for such injection, unless it is for some thing else.
  108. 108. $scope var myApp=angular.module("myModule",[]) .controller("countryController", function($scope){ $scope.name = "India"; }); Controller as syntax var myApp=angular.module("myModule",[]) .controller("countryController", function(){ this.name = "India"; });
  109. 109. CONTROLLER vs SCOPE Though we are using controller as syntax; don’t think that angular won’t use $scope. It is using but it is hiding. That is in controller as syntax we aliasing the controller: myController as myCtrl This cityCtrl is reference variable pointing to the myController. Angular will take this reference and attach to the $scope object.
  110. 110. $scope vs $rootscope $rootScope: Is available globally (for all controllers) $scope: Is available only to the controller that is created.
  111. 111. var myApp = angular.module("myModule", []) .controller("redController", function($scope, $rootScope) { $scope.redColor = "I am Red"; $rootScope.rootScopeColor = "I am Root Scope Color"; }) .controller("greenController", function($scope) { $scope.greenColor ="I am Green"; })
  112. 112. <body> <div ng-controller="redController"> Root Scope : {{ rootScopeColor }}<br> Red Color Controller : {{ redColor }}<br> Green Color Controller :{{ greenColor }} </div> <br> <div ng-controller="greenController"> Root Scope : {{rootScopeColor}}<br> Green Color Controller : {{greenColor}}<br> Red Color Controller :{{redColor}} </div> </body>
  113. 113. Angular $ui-router The ui-router is a 3rd party routing framework for Angular JS ui-router implements routing based on the state of the application where as ngRoute implements routing based on the route URL.
  114. 114. $ui-router vs ngroute ngRoute implements routing based on the route URL that means we use view & routes that are tied to the application URL. ui-router use the routes that are not tied to the application URL that means parts of the sites can be changed even if the URL doesn’t change.
  115. 115. How to get $ui-router
  116. 116. WHAT DO I NEED The first thing you need to do is reference the UI-Router JavaScript file. Get the CDN link from: https://cdnjs.com/libraries/angular-ui-router <script src=“https://cdnjs.cloudflare.com/ajax/libs/angular-ui- router/0.3.2/angular-ui-router.js”></script> (OR) <script src=“https://cdnjs.cloudflare.com/ajax/libs/angular-ui- router/0.3.2/angular-ui-router.min.js”></script>
  117. 117. ADD A MODULE DEPENDENCY ON UI- ROUTER.
  118. 118. $ui-view Directive Finally, you'll need to add a ui-view directive to your page. This is the rough equivalent of using the ngView directive when working with ngRoute. It gives the router a place to insert views into your page.
  119. 119. “ https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.min.js “ >
  120. 120. CONFIGURING STATES Call the config function module, and inject into it the state $stateProvider service that comes with UI- Router. It has two parameters The first parameter to the function is the name you want to give the state. The second parameter to the state function is a configuration object.
  121. 121. CONFIGURING STATES var myApp = angular.module(“myModule”,[‘ui-roter’]) .config(function($stateProvider){ $stateProvider .state(“home” { url: “/home”, templateUrl: “Templates/home.html”, controller: “homeController”, controllerAs: “homeCtrl” }) });
  122. 122. Inline $ui-router var myApp = angular.module(“myModule”,[‘ui-roter’]) .config(function($stateProvider){ $stateProvider .state(“home” { url: “/home”, template: “Hello Angular”, controller: “homeController”, controllerAs: “homeCtrl” }) });
  123. 123. $ui-router Parameters Define the sate with URL parameter .state(“studentDetails”,{ url:”/studentdetail/:id”, templateUrl:”Templates/studentDetails.html”, controller: “studentDetailsController”, controllerAs:”studentDetailsCtrl” })
  124. 124. Link to the state with URL parameter <ul> <li ng-repeat=“studentDetailsCtrl.students”> <a ui-sref=“studentDetails({id:student,id})”></a> </li> </ul> $ui-router Parameters
  125. 125. Read the specific parameter value from controller function, call the web-service method(if any) & id value & then retrieve that specific parameter.( Eg :student details) controller(“studentDetailsController”,function($scope,$stateProvider){ var vm = this; $http({ url:”...”, method: “get”, params:{id:$stateparams.id} }).then(function(response){ vm.student = student.data; }) }) $ui-router Parameters
  126. 126. $ui-router Case-insensitive To make ui-router case insensitive inject $urlMatcherProvider() service into the config() function and call caseInsensitive(true) function. var app = angular .module(“myModule”,[‘ui-router’]) .config(funtion($stateProvider,$urlMatcherPro vider){ $urlMatcherProvider.caseInsentive(true); });
  127. 127. $ui-router Default route To achieve this inject $urlRouterProvider service into config() function & use otherwise function for passing the default route var app = angular .module(“myModule”,[‘ui-router’]) .config(funtion($stateProvider,$urlMatcherProvider,url RouteProvider){ $urlRouterProvider.otherwise(“/home”); });
  128. 128. $ui-router – Active menu item Create a CSS in .css file or style tag .activeClass{ background-color : pink; } Mention “ui-sref-active” directive in anchor tag <a ui-sref=“home” ui-sref-active=“activeClass”> Home </a>
  129. 129. NESTED VIEWS & STATES One of the benefit over ui-router with ng-route is, ui-router provides & supports nested states & views. In nested states, there is parent-child relation i.e., the parent properties are available in all the child states.
  130. 130. HOW TO SPECIFY Can be specify in two ways 1. Using dot notation .state(“home”,{ ----- }) .state(“home.list”,{ --- }) 2. Using the parent property with the parent name as string. .state{“home”,{ --- }) .state(“list”{ parent: “home”, --- })
  131. 131. Initially my home page is displaying some text along with two buttons. Which the buttons are activate the home page along with the activated button data will be displayed.
  132. 132. RESULT
  133. 133. MULTIPLE NAMED VIEWS Another benefit of ui-router is it supports multiple name views. If we define view object state's templateUrl, template and templateProvider will be ignored i.e., Views override state's template properties: that means we create abstract states. So in the case that you need a parent layout of these views, you can define an abstract state that contains a template, and a child state under the layout state that contains the 'views' object.
  134. 134. CREATE NAMED VIEWS
  135. 135. $ui-router MULTIPLE VIEWS UI-Router assigns every view to an absolute name. The structure for this is viewName@stateName. Since our main ui-view inside our about state, we gave it a blank name. The other two views columnOne@about and columnTwo@about having the naming scheme this way let’s us define multiple views inside a single state.
  136. 136. RESULT

Hinweis der Redaktion

  • Two-way binding – sync model and view. A change in model, update the view and vice-versa
  • Angular.js is the only script file that you need for the core Angular features, because Angular has no other dependencies on other libraries.

    So whenever you see ng in your code or in documentation, or in a website name, or a bumper sticker, think Angular. ng-app is what we call the application directive. It is a special directive that Angular looks for inside of your HTML, and if it finds it, Angular will bootstrap itself; so it initializes itself and it jumps into action to start managing the page. Let's try this.
  • My other requirement, though, is to add an ng-app directive somewhere in my markup. Some people like to add that directly to the html element; I could also add it somewhere else inside of the page, like on the body element, but you do only get one ng-app directive per page, and Angular's only going to take control of the section of DOM where that ng-app directive applies. So in this case it will apply to everything in the body; I won't be able to use Angular expressions and features outside of the body tag. But with the script in place and my ng-app directive in place,
  • <div ng-app="" ng-init="quantity=1;cost=5"> <p>Total in dollar: {{ quantity * cost }}</p>

    <p>Total in dollar: {{ 4*2 }}</p> </div>
  • Complex representation
  • The first thing I need to do is create a module and give it a name. I do this with an Angular API, angular.module. Angular, that particular object, is the one single identifier that Angular puts into the global namespace, so I can use it anywhere where angular.js is included. And that Angular object has methods like, .module, that will allow me to create a module or get a reference to an existing module.
  • This empty array tells Angular that our module does not depend on any other modules. Later on, we will add set of dependencies to our module. But for now it has done. The other thing we are doing is capturing that module into a global variable called. This will make it easy for us to create objects inside of this module, such as controllers and services.

  • Example:

    script.js

    var myApp = angular.module('myModule', []);

    index.html
    <!DOCTYPE html>
    <html ng-app = "myModule">
    <head>
    <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js">
    </script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    </head>
    <body >
    <h1>Hello Plunker!</h1>
    {{ 8/4}}
    </body>
    </html>
  • Controllers are one of the central pieces of the Angular framework. With Angular, a controller is in charge or responsible for building a model.

    A model contains the data we need to work with and a controller will do whatever it needs to grab that data.

    So it might need to make some calculations or call back to a web server that talks to a database, whatever it takes. I'll show you how to build a controller that is able to build a model.
  • is a new directive, the ng-controller directive. ng-controller is an attribute that we place into our HTML. So just like ng-app is a directive, ng-controller is another directive. And when we use ng-controller, we can specify the name of a controller that we want to take control of some area of the HTML. So in this code snippet, ng-app will initialize Angular and Angular will take control of that div and everything inside of it. Inside of that div is a child div where we can put something called.

    ng-controller can only be used where we have an ng-app in place, and we have to tell Angular the name of the controller that will be in charge.

    You'll encounter a few things with dollar signs in the front when you work with Angular, and just like the ng prefix, the dollar sign prefix is a sign that the component you're working with is a component provided by Angular. What we can do with the scope argument is assign our model to the object. So $scope is not the model, but things that we attach to that $scope are going to be the model.
  • 'myController’ = name of the controller

    function($scope) – anonymous function – manages the web page invoked by angular

    $scope - assign our model to the object

    Here we are passing the $scope as the parameter to this we attaching the message property. So here the scope is not the model, message property attached to scope is the model which is available in the view by binding expression the model from the scope. That is controller isn’t manipulating the DOM elements directly, it is showing the clean separation between the model, view and the controller.
  • When the HTML renders, the browser is going to see "img src=" and then this binding expression. It's not until later when Angular is up and running, that it comes in and replaces person.imageSrc with the value from my model. But unfortunately, the way the browser works, as soon as it sees "<img src="{{person.imageSrc}}", it's going to go and try to download an image, treating that binding expression as a URL. And in fact, down inside of the Console window here, you can see that each time it refreshed the Preview window, it tried to grab that image and got a 404 error, could not be found.
  • But for now just know that ng-model, an extremely useful directive because you can apply it to inputs, you can apply it to selects, you can apply it to text areas, and what ng-model will do is always keep your data in sync; it's going to move information that the user types into your model. And if for some reason the model changes, it will move that information back into your input.
  • Formng-model.html
  • Formstatusng-model
  • Ng-modelclasses.html

    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <style>
    input.ng-invalid {
    background-color: lightblue;

    }
    </style>
    <body>

    <form ng-app="" name="myForm">
    Enter your name:
    <input name="myName" ng-model="myText" required>
    </form>

    <p>Edit the text field and it will get/lose classes according to the status.</p>
    <p><b>Note:</b> A text field with the "required" attribute is not valid when it is empty.</p>
  • Eg1: ng-options-object.html
    Eg2: ng-options.html

  • <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>

    <div ng-app="myApp" ng-controller="myCtrl">

    <select>
    <option ng-repeat="x in names">{{x}}</option>
    </select>

    </div>

    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
    });
    </script>

    <p>This example shows how to fill a dropdown list using the ng-repeat directive.</p>

    </body>
    </html>
  • Eg: ng-repeat-ex.html
    Eg: ng-options-ex.html
  • <w3TestDirective>
  • Add restrict : "C",
  • var app = angular.module("myApp", []); app.directive("w3TestDirective", function() {     return {         restrict : "A",         template : "<h1>Made by a directive!</h1>"     }; });
  • Ex: filterUppercase.html (lowercase)
    Ex: filterCurrency.html
  • Ex: filterFilter.html
  • Filterdirective.html
  • Primary need of controller is to create model to view. This should do more things. If it does, then it violets the single responsibility principle.
    Eg: If the controller having to compute a page with dob/math value along with building a model, then it violets one of its responsibility.
    This single responsibility logic is injected into external service, that need that services.
  • Locationservice.html
  • he $interval service is AngularJS' version of the window.setInterval function.
    The $interval service runs a function every specified millisecond.
  • The $timeout service is AngularJS' version of the window.setTimeout function.
    The $timeout service runs a function after a sepecified number of milliseconds.
  • The $http service is one of the most common used services in Angular JS applications. The service makes a request to the server, and lets your application handle the response.

    Ex: httpservice.html
  • The way I find out is to call a then method on my promise and pass the then method a function that will be called in the future. The then method will call the function when the data is ready sometime in the future, and it will pass the data into the function as a parameter.

    $http service returns a promise object this means that the functions returns may not be available immediately because we can’t return value of the HTTP servers action.
  • promiseobject.html & sample.html

    $http.get({
    method: ‘GET’
    url: ’ sample.html’
    )}
    .then(function(scope)
    {
    $scope.employee = response.data;
    )};
  • If we want to register a service using the function constructor, in that scenario we will use service() method to register the service. If we use factory() method to register the service it returns the value after execution of the service function. It can return any value like primitive value, function or object. So service() method returns the function object whereas factory() method can return any kind of value.
  • Customeservice1.html
    Customservice1.js
  • A factory() contains two parameters name of the factory method where we create a custom service and an anonymous function
    stringService: name of the factory method
    Function() returns a Java Script object ( a service in a angular is nothing but a JavaScript object with some special properties and functions).
    Usually a service in angular is stateless.

    Now all the logic is in stringService. We can call it by using the processingString method in any controller.
    Now we need to inject this into our controller function
  • $httpget().html
    Sample.html
  • url - We need to send url of http server to perform required operations.
    data - We will use this property to send required parameters to requested url.
    config - By using this property we can change content-type
  • $httppost().html
  • $httpput().html
  • $httpjsonp.html
  • The function in the we pass three parameters- $scope object, $location service (which specifies location of the current web page), $anchorScroll service

    $location service hash() appends the hash (#) fragment to the URL.

    $anchorScroll method reads the hash fragment in the URL & jumps to the element on the page. (automatically scrolls)
  • It's really just a process of a server using a URL to locate some resource and returning it to the client. The URL specifies the route. Routes are basically locations. Prior to the explosion of JavaScript libraries and frameworks, most web applications were executed almost entirely on servers. A client would request a webpage or other resource from the server using a URL and the server retrieves the resource and sends it back to the client. Often this meant that an entire webpage would be sent back to the browser after each request to the server.
  • Client-side routing doesn't replace server-side routing. All web applications still interact heavily with servers and those servers still need to accept a URL and use it to locate and return the resource needed by the client. However, when using a client-side framework like Angular, the requests to the server are of often for smaller bits of information rather than entire webpages and all of their related resources.
  • Let's assume this is the home screen of our new single page Angular app. We've got a title at the top, a few links down the left side and some content in the middle. When the user takes some action like clicking the first link on the left, the application navigates them to a new client-side route and loads information related to that route into a portion of the page. When they click a second link, they may be taken to a new route which loads different information into the same part of the page. These route transitions will often retrieve resources from a server. That could include partial HTML files, JSON data, images or anything else you might normally request from a server. So using client-side routing does not mean that there is no interaction with the server or that the server isn't also locating and returning resources based on its own routes. It just means that the whole page in the browser is no longer being reloaded with every server interaction and that the client application needs a way to find and refer to various locations within the app.
  • If you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module.
  • First, you can install it with bower. Bower is a package manager primarily used for client side code. The command to install ngRoute is bower install angular-route, followed by the hash sign and the version you want.
    You can also use npm to install the file. Npm is the node package manager. It works similarly to bower. The command to install ngRoute with npm is npm install angular-route, followed by the at sign and the version number.
    You can simply add a JavaScript file reference to this URL, and you don't have to bother keeping up with the file in your project at all.
    The last technique I'll mention is to manually download the file and add it to your project. All the Angular code can be found on the code.angularjs.org website.
  • Define the $routeProvider using the config method of your application. Work registered in the config method will be performed when the application is loading.
  • Ex:routing.html
  • Ex: mainroute.html
  • Ex: Inlinerouting.html
  • Finally, the route service has several events that fire at various points in the route transition process. You can handle these events using the on function that exists on the root scope.
  • ngrouteparams.html
    Sample1.htm
    Sample2.htm
  • Routeparams example
  • When accidently we press a navigation link while filling application, then the unsaved data will be losed, To prevent this we will take confirmation message whether we want to navigate or not.
  • Nestedcontroller.html
    Nestedcontroller.js
  • Nestedcontroller.html
    Nestedcontroller.js
  • Nestedcontroller.html
    Nestedcontroller.js
  • rootScope.html
    rootScope.js
  • Inlinetemplate.html
  • the ui-sref we defined in home.html are linked to an actual state. With home.list and home.paragraph created, those links will now take the template provided and inject it into ui-view.

  • The benefit of abstract state is the URL of the parent state is prepended to the URL of the child states, that means we can remove any redundant part from child state’s URL.

×