Welcome to part 4 of my AngularJS tutorial. If you haven’t seen the other videos watch them first.
This time we’ll look at AngularJS services. I’ll create custom services as well as cover built in services like $window, $document, $location, $interval, $log, $exceptionHandler, $watch, $compile, and I’ll use $http to pull in data from a language translation web service. My translation web service was built in this tutorial.
If you like videos like this consider supporting me on Patreon.
[googleplusone]
Code From the Video
angulartut13.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!doctype html> <html ng-app="app13" ng-cloak> <head> <title>AngularJS Tutorial 13</title> <style> [ng\:cloak], [ng-cloak], .ng-cloak { display: none; } .thick { font-weight: bold; } </style> </head> <body> <div ng-controller="mainCtrl"> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script> <script src="js/exam13.js"></script> </body> </html> |
exam13.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/* Services are objects that bundle together methods that serve a specific function. Angular provides many built in services, but it is also easy for us to make our own custom services. */ var app13 = angular.module('app13', []); // Creates a simple service that provides a method // we can use in other controllers, directives and // filters. Services unlike factories don't return // anything, but instead provide access to a // single object that can be used by your entire // application app13.service('HelloService', function(){ this.helloService = function() { console.log('Hello Service'); }; }); // Create a factory that creates an object, adds // a method to it and returns that object app13.factory('HelloFactory', function(){ var factory = {}; factory.helloFactory = function(){ console.log('Hello Factory'); }; return factory; }); // Pass the service into the controller to // access its method app13.controller('mainCtrl', function(HelloService, HelloFactory) { HelloService.helloService(); HelloFactory.helloFactory(); }); |
angulartut14.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
<!doctype html> <html ng-app="app14" ng-cloak> <head> <title>AngularJS Tutorial 14</title> <style> [ng\:cloak], [ng-cloak], .ng-cloak { display: none; } .thick { font-weight: bold; } </style> </head> <body> <div ng-controller="mainCtrl"> <!-- Demonstrate $window --> <input type="text" ng-model="userName" /> <button ng-click="greetUser(userName)">Hello</button> <br><br> <!-- Demonstrate $location --> URL : {{currURL}} <br><br> Protocol : {{theProtocol}} <br><br> Host : {{currHost}} <br><br> Port : {{currPort}} <br><br> Path : {{currPath}} <br><br> Search : {{currSearch}} <br><br> <!-- Updates time using $interval --> Current Time : {{time}} <br><br> <!-- The $log service --> <label>Message: <input type="text" ng-model="message" /></label> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> <button ng-click="$log.debug(message)">debug</button> <br><br> <!-- The $exceptionHandler service --> <button ng-click="throwException()">Throw Exception</button> <br><br> <!-- Angular automatically replaces < and > that is entered by the user to keep them from entering dangerous HTML. <p onmouseover=alert('Doing Bad Stuff')>Do Bad Stuff</p> isn't displayed as HTML unless you use ng-bind-html, but even then onmouseover is stripped away. --> <input type="text" ng-model="badStuff"/> <br><br> <span>{{badStuff}}</span> <span ng-bind-html="badStuff"></span> <span ng-bind="badStuff"></span> <br> <!-- $compile service --> <p get-player-info></p> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script> <!-- Used to allow some HTML to avoid sanitization --> <script src="http:////ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-sanitize.js"></script> <script src="js/exam14.js"></script> </body> </html> |
exam14.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
var app14 = angular.module('app14', ["ngSanitize"]); app14.controller('mainCtrl', function($scope, $window, $location, $interval, $log, $exceptionHandler, $sanitize) { // The $window service provides an object // that represents the window object $scope.greetUser = function(userName){ $window.alert("Hello " + userName); } // The $document service is an object that // represents the window.document object, but // normally if you want to minipulate elements // you'll use angular.element instead // $location is a service that provides access // to the current URL and can be used for // navigation within the document $scope.currURL = $location.absUrl(); // Get the protocol being file or http $scope.theProtocol = $location.protocol(); // Get the host $scope.currHost = $location.host(); // Get the port $scope.currPort = $location.port(); // Set the path $location.path("#/the/path"); // Get the path $scope.currPath = $location.path(); // Set the search $location.search("random=stuff"); // Get the search $scope.currSearch = $location.search(); // The interval service executes code at a set // time being every 2 seconds in this situation $interval(function() { var hour = new Date().getHours(); // Add a starting 0 and then slice the last // to numbers off the string var minutes = ('0' + new Date().getMinutes()).slice(-2); var seconds = ('0' + new Date().getSeconds()).slice(-2); $scope.time = hour + ":" + minutes + ":" + seconds; }, 2000); // Log messages to the console for debugging $scope.$log = $log; // Any uncaught exception delegates to the // $exceptionHandler service which outputs // to the console. $scope.throwException = function() { // If we didn't catch the exception a stack // trace would print in the console try { throw new Error("Exception Thrown"); } catch(e) { // Receives the exception and a string // explaining the exception $exceptionHandler(e.message, "Caught Exception"); } } $scope.badStuff = ""; // Monitors a change in value for badStuff // and sanitizes it $scope.$watch("badStuff", function(value) { $scope.htmlData = $sanitize(value); }); // Data used by compile below $scope.players = [{name: "Barry Bonds", avg: 0.298, hr: 762, obp: 0.444}, {name: "Hank Aaron", avg: 0.305, hr: 755, obp: 0.374}, {name: "Babe Ruth", avg: 0.342, hr: 714, obp: 0.474}, {name: "Ted Williams", avg: 0.344, hr: 521, obp: 0.482}]; }); // The $compile service compiles HTML into a // template using scope data // This replaces get-player-info in the document // app14.directive("getPlayerInfo", function($compile) { return function(scope, element, attrs){ // The template var playerList = "<ul><li ng-repeat='player in players'>{{player.name}}</li></ul>"; // Wrap it in a jqLite object var listElem = angular.element(playerList); // Create the compile function which // generates are HTML var compileFunc = $compile(listElem); // Process our content compileFunc(scope); // Update our jqLite object and add it to the // document element.append(listElem); } }); |
angulartut15.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<!doctype html> <html ng-app="app15" ng-cloak> <head> <title>AngularJS Tutorial 15</title> <style> [ng\:cloak], [ng-cloak], .ng-cloak { display: none; } .thick { font-weight: bold; } </style> </head> <body> <div ng-controller="mainCtrl"> <button ng-click="getData()">Get Data</button> <br><br> <!-- Display raw JSON --> {{players}} <!-- Put JSON in a list --> <ul> <li ng-repeat="player in players"> {{ player.name + " hit " + player.hr + " Home Runs"}} </li> </ul> <br> Translate : <input type="text" ng-model="wordsToTranslate"/> <br><br> <button ng-click="translate()">Translate</button> <br><br> {{translated}} </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script> <script src="js/exam15.js"></script> </body> </html> |
exam15.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
var app15 = angular.module('app15', []); app15.controller('mainCtrl', function($scope, $http) { // Get data from the json file and display it $scope.getData = function() { $http.get("playerData.json").success( function(data){ $scope.players = data; } ); } // Get this Chrome extension if you get the // CORS error // Allow-Control-Allow-Origin $scope.translate = function() { var words = $scope.wordsToTranslate.replace(/ /g,"+"); var jsonUrl = "http://newjustin.com/translateit.php?action=translations&english_words=" + words; $http.get(jsonUrl).success( function(data){ $scope.translated = data; } ); } }); |
playerData.json
1 2 3 4 |
[{"name": "Barry Bonds", "avg": 0.298, "hr": 762, "obp": 0.444}, {"name": "Hank Aaron", "avg": 0.305, "hr": 755, "obp": 0.374}, {"name": "Babe Ruth", "avg": 0.342, "hr": 714, "obp": 0.474}, {"name": "Ted Williams", "avg": 0.344, "hr": 521, "obp": 0.482}] |
Leave a Reply