Skip to content

Instantly share code, notes, and snippets.

@iplus26
Created July 3, 2016 05:27
Show Gist options
  • Save iplus26/49f39db1c17785596ed670d9238dc714 to your computer and use it in GitHub Desktop.
Save iplus26/49f39db1c17785596ed670d9238dc714 to your computer and use it in GitHub Desktop.
This gist is created by Ivan Jiang and used to test whether service and factory in AngularJS is singleton or not.
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<meta name="description" content="This jsbin is created by Ivan Jiang and used to test whether service and factory in AngularJS is singleton or not. ">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script src="singletonLog.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test AngularJS Singleton Service/Factory</title>
</head>
<body>
<div id="testSingletonFactory">
<factory-log></factory-log>
<another-factory-log></another-factory-log>
</div>
<div id="testSingletonService">
<service-log></service-log>
<another-service-log></another-service-log>
</div>
</body>
</html>
var app = angular.module('myApp', []);
app.factory('singletonLogFactory', function(){
console.log('Factory: This should only log once. ');
return { foo: 'bar', };
});
app.service('singletonLogService', function() {
console.log('Service: This should only log once. ');
this.foo = 'bar';
});
// factory
app.directive('factoryLog', function(singletonLogFactory) {
return {
template: 'This is log: ' + singletonLogFactory.foo,
};
});
app.directive('anotherFactoryLog', function(singletonLogFactory) {
return {
template: 'anotherLog: ' + singletonLogFactory.foo,
};
});
// service
app.directive('serviceLog', function(singletonLogService) {
return {
template: 'This is log: ' + singletonLogService.foo,
};
});
app.directive('anotherServiceLog', function(singletonLogService) {
return {
template: 'anotherLog: ' + singletonLogService.foo,
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment