Services

Services in Angular are substitutable objects that are wired together using Dependency Injection

  • lazy instantiated : Angular only instantiates a service when an app component depends on it
  • Singletons : Each component that depends on a services get a reference to the single isntane generated by the service factory.

Angular offers server useful services ( such as $http ), but in most cases you will want to create your own.

all built in services start with $. e.g. $http

the service factory function is usually represented by a single object that is passed into other controllers or services.


<hr>

example of Angular Factory being used:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>services</title>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
</head>

<body>
<div ng-app="app">
  <h1>Services</h1>

  <div ng-controller="ListCtrl as list">
    <p ng-repeat="message in list.messages">: </p>
  </div>

  <div ng-controller="PostCtrl as post">
    <form ng-submit="post.addMessage(post.newMessage)">
      <input type="text" ng-model="post.newMessage">
      <button type="submit">add msg</button>
    </form>
  </div>

</div>

<script>
  // Module
  //
  angular.module('app', []);


  // Factory
  //
  angular.module('app').factory('messages', function() {
    var messages = {};

    messages.list = []; // store msgs here

    messages.add = function(message) {
      messages.list.push({id: messages.list.length, text: message});
    };

    return messages;
  });


  // Controllers
  //
  angular.module('app').controller('ListCtrl', function(messages) {
    var self = this;

    self.messages = messages.list;
  });

  angular.module('app').controller('PostCtrl', function(messages) {
    var self = this;

    self.newMessage = 'hello thur!';

    self.addMessage = function(message) {
      messages.add(message);
      self.newMessage = '';
    };
  });


</script>
</body>

</html>