Currently, I am in the process of working on a project that requires me to access a service from outside the Angular service. Unfortunately, it seems that the service retrieved from outside of Angular is not the same instance as the one inside the application. In fact, it creates a new instance every time I invoke it. Below, I have created an example to illustrate this issue.
<div ng-controller="controller">
<div>
<span ng-bind="count"></span>
<input type="button" value="Inside" ng-click="inc()"></input>
</div>
<div>
<span id="outside-count">0</span>
<input type="button" value="Outside" onclick="outside()"></input>
</div>
</div>
Here is the corresponding JavaScript code:
angular.module('Services', [])
.service('svc', function() {
var svc = {
count: 0,
increment: function(){svc.count++;}
};
return svc;
});
angular.module('MyApp', ['Services'])
.controller('controller', ['$scope', 'svc', function($scope, svc) {
$scope.count = svc.count;
$scope.inc = function() {
svc.increment();
$scope.count = svc.count;
};
}]);
var outside = function() {
var svc = angular.injector(['ng', 'Services']).get('svc');
svc.increment();
angular.scope().$apply();
document.getElementById('outside-count').innerHTML = svc.count;
};
My expectation was that the outside count button would increment the same service object as the one I get in the ng-controller
. However, it creates a new instance every time, with consecutive clicks on the button always displaying 1
. The "Inside" button, on the other hand, continues to increment the single service as expected.
Is there an alternative way for me to access the service from outside Angular in order to get the singleton instance of the service?
Here is a fiddle of the provided code.