Home
Tutorials
Microsoft Technologies Tutorials
Java Programming Tutorials
Web Designing Tutorials
Script Programming Tutorials
Database Programming Tutorials
Mobile Technologies Tutorials
Other Programming Tutorials
Examples
Articles
Tools
News
AngularJS Factory Service Example
Keywords : Angularjs factory example, How to use factory service in angularjs with example, Angularjs app.factory service example, AngularJS use factory instead of service example
Example
<!DOCTYPE html> <html> <head> <title> AngularJs Factory Service Example </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script type="text/javascript"> var app = angular.module('myApp', []); // Creating Factory app.factory('myFactory', function () { var displayFact; var addMSG = function (msg) { displayFact = ' Hi Guest, Welcome to ' + msg; } return { setMSG: function (msg) { addMSG(msg); }, getMSG: function () { return displayFact; } }; }); // Creating Service app.service('myService', function () { var displayServ; var addMSG = function (msg) { displayServ = 'Hi Guest, Welcome to ' + msg; } this.setMSG = function (msg) { addMSG(msg); } this.getMSG = function () { return displayServ; } }); app.controller("myCtrl", function ($scope, myService, myFactory) { //Inject factory and service both to controller. myFactory.setMSG("Tutlane (with Factory)"); myService.setMSG("Tutlane (with Service)"); //Prepare a collection $scope.myCollections = [ myFactory.getMSG(), myService.getMSG() ]; }); </script> </head> <body> <h2>AngularJS Factory Service Example</h2> <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="coll in myCollections"> {{coll}} </div> </div> </body> </html>
Click Here to See Result
Result
Previous
Next