AngularJS Service
AngularJS Service
It’s quite similar with Spring Service.
This is documentation AngularJS : Developer Guide
Example
- app.js
- controller.js
- service.js
- /service/serviceimpl.js
Create Module
Controller and use Service
Register service
Service Implementation
app.js
Create Module
var TestModule = angular.module("TestModule",[]); // Create module
servie.js
(function(module){ 'use strict'; module.factory('ServiceImpl',function($rootScope, $http){ return new app.ServiceImpl($rootScope, $http); // $http }); // module.service('ServiceImpl',['$rootScope','$http',app.ServiceImpl]); }(TestModule));
Register ServiceImpl as named “ServiceImpl” This has $rootScope and $http module.
serviceimpl.js
This is implementation of service.
init, prototype, and add method for it.
(function(app){ 'use strict'; var ServiceImpl = function($scope, $http) { this.init($scope, $http); } var p = ServiceImpl.prototype; p.init = function($scope,$http){ this.$http = $http; this.$scope = $scope; }; p.getData = function(callback){ this.$http({ method : 'GET', url : '/listitem', params : { method: 'list' } }).success(function(response,status,headers,config,statusText){ console.log(config); callback.call(this,response.data); }); }; app.ServiceImpl = ServiceImpl; }(this.app));
controller.js
(function(module){ 'use strict'; // Strict mode module.controller('pageController', function($scope){ $scope.changePage = function(type){ }); }); module.controller('listController', function($scope){ ServiceImpl.getData(function(list){ $scope.items = list; }); }); }(TestModule));
Use
Use them
This example is nodejs express
<!DOCTYPE html> <html> <head> <title>TODO</title> <link rel='stylesheet' href='/bower/bootstrap/dist/css/bootstrap.css' /> <script src="/bower/angular/angular.min.js"></script> <script type="text/javascript" src="/javascripts/app/service/ServiceImpl.js"></script> <script type="text/javascript" src="/javascripts/app/app.js"></script> <script type="text/javascript" src="/javascripts/app/service.js"></script> <script type="text/javascript" src="/javascripts/app/controller.js"></script> </head> <body ng-app="todoModule" ng-controller="pageController"> </body> </html>