¿Cómo crear archivos de controlador AngularJS separados?

Resuelto Beebunny asked hace 10 años • 6 respuestas

Tengo todos mis controladores AngularJS en un archivo, controladores.js. Este archivo está estructurado de la siguiente manera:

angular.module('myApp.controllers', [])
  .controller('Ctrl1', ['$scope', '$http', function($scope, $http) {    
  }])
  .controller('Ctrl2', ['$scope', '$http', function($scope, $http) }
  }])

Lo que me gustaría hacer es poner Ctrl1 y Ctrl2 en archivos separados. Luego incluiría ambos archivos en mi index.html, pero ¿cómo debería estructurarse? Intenté hacer algo como esto y arroja un error en la consola del navegador web que dice que no puede encontrar mis controladores. ¿Alguna pista?

Busqué en StackOverflow y encontré esta pregunta similar; sin embargo, esta sintaxis utiliza un marco diferente (CoffeeScript) además de Angular, por lo que no he podido seguirla.


AngularJS: ¿Cómo creo controladores en varios archivos?

Beebunny avatar Nov 20 '13 11:11 Beebunny
Aceptado

Archivo uno:

angular.module('myApp.controllers', []);

Archivo dos:

angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){

}]);

Archivo tres:

angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){

}]);

Incluir en ese orden. Recomiendo 3 archivos para que la declaración del módulo sea independiente.


En cuanto a la estructura de carpetas hay muchísimas opiniones sobre el tema, pero estas dos son bastante buenas.

https://github.com/angular/angular-seed

http://briantford.com/blog/huuuuuge-angular-apps.html

Fresheyeball avatar Nov 20 '2013 04:11 Fresheyeball

El uso de la API angular.module con una matriz al final le indicará a angular que cree un nuevo módulo:

miApp.js

// It is like saying "create a new module"
angular.module('myApp.controllers', []); // Notice the empty array at the end here

Usarlo sin la matriz es en realidad una función captadora. Entonces, para separar tus controladores, puedes hacer:

Ctrl1.js

// It is just like saying "get this module and create a controller"
angular.module('myApp.controllers').controller('Ctrlr1', ['$scope', '$http', function($scope, $http) {}]);

Ctrl2.js

angular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);

Durante sus importaciones de JavaScript, solo asegúrese de que myApp.js esté después de AngularJS pero antes de cualquier controlador/servicio/etc... de lo contrario, angular no podrá inicializar sus controladores.

Jimmy Au avatar Nov 20 '2013 05:11 Jimmy Au

Aunque ambas respuestas son técnicamente correctas, quiero presentar una opción de sintaxis diferente para esta respuesta. En mi humilde opinión, esto hace que sea más fácil leer lo que sucede con la inyección, diferenciar entre etc.

Archivo uno

// Create the module that deals with controllers
angular.module('myApp.controllers', []);

Archivo dos

// Here we get the module we created in file one
angular.module('myApp.controllers')

// We are adding a function called Ctrl1
// to the module we got in the line above
.controller('Ctrl1', Ctrl1);

// Inject my dependencies
Ctrl1.$inject = ['$scope', '$http'];

// Now create our controller function with all necessary logic
function Ctrl1($scope, $http) {
  // Logic here
}

Archivo tres

// Here we get the module we created in file one
angular.module('myApp.controllers')

// We are adding a function called Ctrl2
// to the module we got in the line above
.controller('Ctrl2', Ctrl2);

// Inject my dependencies
Ctrl2.$inject = ['$scope', '$http'];

// Now create our controller function with all necessary logic
function Ctrl2($scope, $http) {
  // Logic here
}
thank_you avatar Jan 21 '2015 04:01 thank_you