If I understand correctly, you want to isolate scopes of instances of ServiceY
:
-
controller_A
and controller_B
share an instance (let's call it ISY1
for reference purposes);
-
controller_C
and controller_D
share another instance ( ISY2
).
I would then suggest using a factory instead of a service . The feature that defines a service is the fact that this is a singleton - a single instance; factories create a new instance for each consumer object (in this case, one instance per control).
Following is an example that implements a factory with a method, register()
, where a parameter indicates the instance to be shared:
ClickRuntoseeitinaction:
angular.module('myApp', [])
.factory('factoryCompartilhada', function () {
var itens = {}; // coleção de instâncias
return {
register: function (codigo) {
if (!itens[codigo]) // se não existe,
itens[codigo] = {dado: codigo}; // cria instância
return itens[codigo]; // retorna instância
}
}
})
.controller('ctrlA', function ($scope, factoryCompartilhada) {
$scope.instanciaFactory = factoryCompartilhada.register('ISY1');
})
.controller('ctrlB', function ($scope, factoryCompartilhada) {
$scope.instanciaFactory = factoryCompartilhada.register('ISY1');
})
.controller('ctrlC', function ($scope, factoryCompartilhada) {
$scope.instanciaFactory = factoryCompartilhada.register('ISY2');
})
.controller('ctrlD', function ($scope, factoryCompartilhada) {
$scope.instanciaFactory = factoryCompartilhada.register('ISY2');
})
;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script><divng-app="myApp">
<div ng-controller='ctrlA'>
Controller_A: <input ng-model='instanciaFactory.dado' />
</div>
<div ng-controller='ctrlB'>
Controller_B: <input ng-model='instanciaFactory.dado' />
</div>
<div ng-controller='ctrlC'>
Controller_C: <input ng-model='instanciaFactory.dado' />
</div>
<div ng-controller='ctrlD'>
Controller_D: <input ng-model='instanciaFactory.dado' />
</div>
</div>