Friday, January 3, 2014

services and providers setup in AngularJS

I show off prep for services and providers by refactoring the AngularJS app.js here to pull what was the .config stuff into the providers injection. One configures a service by preparing its provider as seen here:

define(["angular",
   
/* filters, directives, services, controllers */
   "filters",
   "services",
   "otherservice",
   "directives",
   "controllers",
   
/* submodules */
   "angular-route"
], function(angular, filters, services, otherservice, directives, controllers) {
   "use strict";
   var app = angular.module('myApp', ['ngRoute', 'myApp.filters', 'myApp.services',
         'myApp.directives', 'myApp.controllers']);
   app.service("$somethingElse", otherservice);
   appConfig.$inject = ["$locationProvider", "$routeProvider"];
   function appConfig($locationProvider, $routeProvider) {
      $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
      $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
      $routeProvider.otherwise({redirectTo: '/view1'});
   }
   app.config(appConfig);
   appRun.$inject = ["$rootScope", "$somethingElse"];
   function appRun($rootScope, $somethingElse) {
      $somethingElse.helloWorld();
   }
   app.run(appRun);
   return app;
});

 
 

I also brought in a new service in a new file called otherservice.js which I put in the js folder along with everything else.

define([], function() {
   function otherService() {
   }
   otherService.prototype.helloWorld = function() {
      alert('Hello World');
   };
   return otherService;
});

 
 

The services injection in app.js above shows off calling the helloWorld method exclusively upon the launch of the application (the refresh of the browser).

No comments:

Post a Comment