Is it necessary to divide responsibilities of a controller in AngularJS?

6

I am creating an ABM with AngularJS, I have a controller usuario.controller.js that has the responsibility to create, delete and display the list of users. The problem is that every time I load the view create the controller is re-instantiated and asks for the list of users again.

That is, the request for the list of users is made in the list view and in the create view. I am loading them dynamically using

asked by Bernardo Coutinho 18.12.2015 в 02:25
source

3 answers

2

If you do not mind sacrificing a little the fidelity of the data in the list (because they are not updated so often) Angular's $http service has an internal cache.

You use it like that.

$http.get("/usuarios", { cache: true } ).then(function(response) { ... });

Using the cache, the difference between using one or more controllers changes other aspects of the system (such as maintenance) but not access to the data, because you have delegated responsibility to another component. The design that is usually used ... varies from one system to another. For example: If you are talking about a list of medical emergencies, this solution would not work.

Since in your question, you did not say how you access the data, if you are using $resource , you can also use the cache

// defines el $resource
var listaLocalDeUsuarios;
var Usuarios = $resource('/usuarios/:id', {}, { 
   lista: { method:'GET', isArray: true, cache: true }
});
Usuarios.lista(function(listado) { listaLocalDeUsuarios = listado }); 
    
answered by 18.12.2015 в 03:10
2

Yes, the best thing is that you have one controller per component, if you want to show several users in a table you can make a table with the list of users, if you want to edit a user you can make a component that is a user form that only require the request of a user and not the entire list. This way you save unnecessary calls to the server and your components are reusable.

    
answered by 16.01.2016 в 04:25
0

The controller should only be used to interact with the user interface components of the component in question, ie, it is the API that is declared for the functionalities, click a button, order a list, open a dialog, etc.

For the case that you describe, you should use the "service", who is in charge of storing the data model and declaring the operations, consumption of services, business logic. The service to be singleton will be executed once, thus maintaining the state of the data, as well as the execution of operations at the moment of loading the application.

As an example I declare a service:

(function(){
  //Las dependencias incluidas en la declaracion del servicio son usadas
  function myService(inyecto, multiples, dependencias, notificacion){
    //Declaro mis funciones, sin preocuparme por la estructura del servicio. De esta manera tenemos un codigo mejor estructurado
    function crear(){
      //Mis operaciones
      //Como resultado de algunas operaciones puedo invocar otros servicios. De esta forma dividimos responsabilidades
      notificacion.notificacionSatisfactoria('Usuario Creado Correctamente')
    }

    function editar(){
      //Mis operaciones
    }

    function consultar(){
      //Mis operaciones
      //Como resultado de las operaciones actualizo el modelo de datos, el cual puede estar en el mismo servicio, o en otro.
      service.usuario = resultadoDeConsulta;
    }

    function eliminar(){
      //Mis operaciones
    }
    //Empaquetamos nuestras operaciones y variables, y las declaramos como publicas. 
    var service = {}
    service.usuario;
    service.crear = crear;
    service.crear = editar;
    service.crear = consultar;
    service.crear = eliminar;
    return service;
}


 //Declaro mi servicio al final del archivo, esto me ayuda a concentrarme en las operaciones.
 angular.module('myApp')
        .service('myService', myService);
//Inyecto las dependencias necesarias para el funcionamiento de mi servicio
myService.$inject = ['inyecto','multiples','dependencias','notificacion'];

 })();

In my controller I limit myself to using the services, being able to reuse both the controller and the services, without the problem of duplication of operations

    
answered by 29.07.2017 в 01:16