I have two controller which injected one service and one factory. As per my knowledge if we change in Service data, It should reflected in whole application but this should not with factory.
My Requirements
For Service:
Service is singleton so if I made changes in Service object that should reflect through out application.
For Factory:
Factory is just function which return something, if I made changes in factory object that it should reflect only current instance not to whole application
I have create an application where I have used two different controller which injected with same service and factory which have two properties.
When I am changing the service property, it is not going to update in other controller.
Following is the code on Plunker
.
Can anyone help on this and provide the code where service will reflect the data but factory not. thanks
(function() {
'use strict';
var app = angular.module('myApp', []);
app.factory('MyFactory', function() {
var myFactory = {};
myFactory.myProperty = { myText: 'Hello' };
myFactory.setProperty = function(value) {
this.myProperty.myText = value;
};
return myFactory;
});
app.service('MyService', function() {
this.myProperty = { myText: 'Test'} ;
this.setProperty = function(value) {
this.myProperty.myText = value;
}
});
app.controller('DummyController', DummyController);
DummyController.$Inject = ['$scope', 'MyFactory', 'MyService'];
app.controller('Dummy1Controller', Dummy1Controller);
Dummy1Controller.$Inject = ['$scope', 'MyFactory', 'MyService'];
function DummyController($scope, MyFactory, MyService) {
$scope.property = MyFactory.myProperty;
$scope.property1 = MyService.myProperty;
}
function Dummy1Controller($scope, MyFactory, MyService) {
MyFactory.setProperty('World1144');
$scope.property = MyFactory.myProperty;
MyService.setProperty('World1144');
$scope.property1 = MyService.myProperty;
}
})();
and relevant part of HTML
<div class="panel-body">
<div ng-controller='DummyController' class='col-md-6'>
<form class="form-inline" role="form">
DummyController
<div>
Current Factory Value :
<input type='text' ng-model='property.myText'>
<br> Current Service Value :
<input type='text' ng-model='property1.myText'>
</div>
</form>
</div>
<hr>
<div ng-controller='Dummy1Controller' class='col-md-6'>
<form class="form-inline" role="form">
Dummy1Controller
<div>
Current Factory Value :
<input type='text' ng-model='property.myText'>
<br> Current Service Value :
<input type='text' ng-model='property1.myText'>
</div>
</form>
</div>
</div>