Doubt on angular services

3

A clue please, if I have a service ServiceY and this service has a ServiceY.nome attribute. In the same screen I have four controller , being: controller_A , controller_B , controller_C and controller_D and the four controller use the same service.

When I am in controller_A and do a certain action, if I am a value within ServiceY.nome , in controller_B I make a get of the present value in ServiceY.nome previously passed and I get the correct result.

Now within controller_C I'll set ServiceY.nome and in controller_D I'll read this attribute, however I do not want to change the values of controller_A and controller_B . What would be the best way to do this?

    
asked by anonymous 16.05.2017 / 14:40

1 answer

5

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>
    
16.05.2017 / 15:18