AngularJS – Service

Introduction

I’ve recently begun a couple of freelance projects on what is a fairly new technology to me – AngularJS.  This post details my reflections on how to write an Angular service and an to provide an explanation.

Definition and Examples

From the Angular site I found this very good explanation:

“The purpose of a service factory function is to generate a single object or function that represents the service to the rest of the application. That object or function will then be passed as a parameter to any other factory function which specifies a dependency on this service.
Angular factory functions are executed lazily. That is, they are only executed when needed to satisfy a dependency, and are then executed exactly once for each service. Everything which is dependent on this service gets a reference to the single instance generated by the service factory.”

 

Jacob Mumm provides a great explanation to the creation of Angular Services either by creating a new function object or a factory, and for the full example, have a look at this jsfiddle.

 I’ll quote the script at length:

The first approach is to use .service(), which creates a new function object.

app.service('nametrickService', function() {
  this.reverse = function(name) {
    return name.split("").reverse().join("");
  };
});

 The alternative method is .factory(), which gives you a space to run some one-time code prior to returning an object.

app.factory('nametrickFactory', function() {
  return {
    reverse : function(name) {
      return name.split("").reverse().join("");
    }
  }
});

To use the sevices we have to inject the named serves into our controller:

app.controller( 'AppCtrl', function AppCtrl($scope, nametrickService, nametrickFactory) {
  $scope.name = 'Guest';
  $scope.reverseNameService = function() {
    $scope.name = nametrickService.reverse($scope.name);  
  };
  $scope.reverseNameFactory = function() {
    $scope.name = nametrickFactory.reverse($scope.name);  
  };
});

  Bower

If using Yeoman a service can be stubbed out by simply entering the following into the terminal console:

 yo angular:service myService

Conclusion

This is a pretty much a rough and ready introduction and an aide-mémoire for myself, I should provide a set of Angular posts over the next week.

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s