web-dev-qa-db-fra.com

Comment créer des fichiers de contrôleur AngularJS distincts?

J'ai tous mes contrôleurs AngularJS dans un seul fichier, controllers.js. Ce fichier est structuré comme suit:

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

Ce que j'aimerais faire, c'est mettre Ctrl1 et Ctrl2 dans des fichiers séparés. J'inclurais alors les deux fichiers dans mon index.html, mais comment devrait-il être structuré? J'ai essayé de faire quelque chose comme ça et une erreur s'est produite dans la console du navigateur Web en disant qu'il ne peut pas trouver mes contrôleurs. Des allusions?

J'ai cherché StackOverflow et trouvé cette question similaire - cependant, cette syntaxe utilise un framework différent (CoffeeScript) au-dessus de Angular, et je n'ai donc pas pu suivre.


AngularJS: Comment créer des contrôleurs dans plusieurs fichiers

314
Beebunny

Premier fichier:

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

Fichier deux:

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

}]);

Fichier trois:

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

}]);

Inclure dans cet ordre. Je recommande 3 fichiers pour que la déclaration du module soit autonome.


En ce qui concerne la structure des dossiers, il existe de nombreuses opinions sur le sujet, mais elles sont plutôt bonnes.

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

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

396
Fresheyeball

L'utilisation de l'API angular.module avec un tableau à la fin indiquera à angular de créer un nouveau module:

myApp.js

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

Son utilisation sans le tableau est en réalité une fonction de lecture. Donc, pour séparer vos contrôleurs, vous pouvez faire:

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) {}]);

Lors de vos importations javascript, assurez-vous que myApp.js se situe après AngularJS mais avant tout contrôleur/service/etc ... sinon angular ne pourra pas initialiser vos contrôleurs.

177
Jimmy Au

Bien que les deux réponses soient techniquement correctes, je souhaite introduire un choix de syntaxe différente pour cette réponse. Cet imho facilite la lecture de l'injection, la différenciation, etc.

Premier fichier

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

Fichier deux

// 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
}

Fichier trois

// 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
}
49
jason328

Qu'en est-il de cette solution? Modules et contrôleurs dans les fichiers (à la fin de la page) Cela fonctionne avec plusieurs contrôleurs, directives et ainsi de suite:

app.js

var app = angular.module("myApp", ['deps']);

myCtrl.js

app.controller("myCtrl", function($scope) { ..});

html

<script src="app.js"></script>
<script src="myCtrl.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

Google a également un Recommandations de bonne pratique pour Angular Structure d'application J'aime vraiment grouper par contexte. Pas tout le code HTML dans un dossier, mais par exemple tous les fichiers pour la connexion (HTML, CSS, app.js, controller.js, etc.). Donc, si je travaille sur un module, toutes les directives sont plus faciles à trouver.

16
schasoli

Pour simplifier, voici un exemple ES2015 qui ne repose pas sur des variables globales

// controllers/example-controller.js

export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
  // something... 
}

// controllers/another-controller.js

export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
  // functionality... 
}

// app.js

import angular from "angular";

import {
  ExampleControllerName,
  ExampleController
} = "./controllers/example-controller";

import {
  AnotherControllerName,
  AnotherController
} = "./controllers/another-controller";

angular.module("myApp", [/* deps */])
  .controller(ExampleControllerName, ExampleController)
  .controller(AnotherControllerName, AnotherController)
2
Pete TNT

Pas si gracieux, mais la solution de mise en œuvre la plus simple qui soit - en utilisant une variable globale.

Dans le "premier" fichier:


window.myApp = angular.module("myApp", [])
....

dans les "deuxième", "troisième", etc.:


myApp.controller('MyController', function($scope) {
    .... 
    }); 
0
user3682640