如何在AngularJS的单独文件中包含控制器 [英] How to have controllers in separate file in AngularJS

查看:40
本文介绍了如何在AngularJS的单独文件中包含控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我四处张望,没有找到适合我当前情况的答案.我有一个app.js文件:

I look around a bit and didn't find an answer that fit with my current situation. I have a app.js file:

'use strict';

var demoApp = angular.module('demoApp', [
    // Dépendances du "module" <-- demoApp
    'ngRoute',
    'routeAppControllers',
    'todoList'
]);

demoApp.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) { 

        // Système de routage
        $routeProvider
        .when('/home', {
            templateUrl: 'views/home.html',
            controller: 'homeCtrl'
        })
        .when('/contact/:msg?', {
            templateUrl: 'views/contact.html',
            controller: 'contactCtrl'
        })
        .when('/todolist', {
            templateUrl: 'views/todolist.html',
            controller: 'listeCtrl'
        })
        .when('/testfiltre', {
            templateUrl: 'views/testfiltre.html',
            controller: 'demoFiltreCtrl'
        })
        .when('/testCreationfiltre', {
            templateUrl: 'views/testcreationfiltre.html',
            controller: 'demoCreationFiltreCtrl'
        })
        .otherwise({
            redirectTo: '/home'
        });
    }
]);



var routeAppControllers = angular.module('routeAppControllers', []);

routeAppControllers.controller('homeCtrl', ['$scope',
    function($scope){
        $scope.message = "Bienvenue sur la page d'accueil";
    }
]);

routeAppControllers.controller('contactCtrl', ['$scope','$routeParams',
    function($scope, $routeParams){
        $scope.message = "Laissez-nous un message sur la page de contact !";
        $scope.msg = $routeParams.msg || "Bonne chance pour cette nouvelle appli !";
    }
]);

routeAppControllers.controller('listeCtrl', [function(){}]);

我在todolist_controller.js中有一个todolist模块:

I have todolist module in todolist_controller.js:

var todoList=angular.module('todoList',[]);

todoList.controller('todoCtrl', ['$scope',
    function ($scope) {

        var todos = $scope.todos = [];

        $scope.addTodo = function () {
            var newTodo = $scope.newTodo.trim();
            if (!newTodo.length) {
                return;
            }
            todos.push({
                title: newTodo,
                completed: false
            });

            $scope.newTodo = '';
        };

        $scope.removeTodo = function (todo) {
            todos.splice(todos.indexOf(todo), 1);
        };

        $scope.markAll = function (completed) {
            todos.forEach(function (todo) {
                todo.completed = completed;
            });
        };

        $scope.clearCompletedTodos = function () {
            $scope.todos = todos = todos.filter(function (todo) {
                return !todo.completed;
            });
        };
    }
]);

我有我的index.html页面:

I have my index.html page:

<!DOCTYPE html>
    <html lang="fr" ng-app="demoApp">
        <head>
            <meta charset="utf-8" />
            <title>Demo App</title>        
            <link rel="stylesheet" href="styles/style.css">
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.4.2/angular-locale_fr-ca.min.js"></script>
            <script src="scripts/controllers/app.js"></script>
            <script src="scripts/controllers/todolist_controllers.js"></script>
        </head>
        <body>
            <div ng-view>
            </div>
            <nav>
                <a href="#/home" class="btn btn-primary">Page d'accueil</a>
                <a href="#/contact" class="btn btn-success">Page de contact</a>
                <a href="#/todolist" class="btn btn-primary">Todo list</a>
                <a href="#/testfiltre" class="btn btn-success">test filtre</a>
                <a href="#/testCreationfiltre" class="btn btn-primary">test création filtre</a>
            </nav>
        </body>
    </html>

我读到我想调用,例如,我的主模块App和所有其他模块文件应以以下开头:angular.module('App').controller(...

I read that I'm suppose to call, for example, my main module App and all my other module file should start with: angular.module('App').controller(...

但是,这意味着如果我将应用程序的名称从"app"更改为"my_app",则必须经过所有控制器并将"app"更改为"my-app".

But, this would imply that if I change the name of my app from 'app' to 'my_app' for example, I would have to go trough all my controllers and change 'app' for 'my-app'.

我想避免这种情况,只能将我的文件导入index.html中,而只需要在我的"app"模块的依赖项中对其进行声明即可.

I would like to avoid that and just be able to import my file in index.html and just have to declare it in the dependencies of my 'app' module.

推荐答案

角度结构

构建有角度的应用程序时,应尽可能分开以使代码易于阅读.您应该为Web应用程序的每个页面/部分创建一个模块.

Angular Structure

When you build an angular app you should separate as much as possible to give your code readability. You should create a module for each page/part of your web app.

此处是此类结构的示例,我编写了该结构并将其用作基础结构角度应用程序.

Here is an example of this type of structure, I wrote this and use it as a base for angular apps.

此文件夹包含您的所有组件和路线.

This folder holds all of your components and routes.

此文件具有您项目的状态,并且是其自己的模块

This file has the states of your project and is its own module

此文件只是您可以将所有其他模块称为依赖项的基础.

This file is just the base where you can call all your other modules as dependencies.

var app = angular.module("myApp",   [
                                    'ui.bootstrap',
                                    'ngAnimate',
                                    'myAppRouter',
                                    'myAppHomeCtrl',
                                    'myAppHomeService',
                                    'myAppNavbarDirective',
                                    'myAppNavbarService',
                                    'myAppLoginCtrl',
                                    'myAppLoginService'
                                ]);

您可以在此处看到所有编写和添加的不同模块.看到这个叫做myApp的方式了吗?好吧,我们称其为html

You can see all of the different modules written and added here. See the way this is called myApp? well we call that part in the html

<html ng-app="myApp">

组件

这将包含诸如"home"和"contact"之类的内容,这些文件夹应包含少量所需的html,控制器和服务中的所有内容.

components

this will contain things like "home" and "contact" these folders should have everything then need in little self contained html, controllers and services.

这确实可以回答您的问题,为您执行的控制器添加新模块,如下所示.

This is the bit that really answers your question, to add a new module for a controller you do as follows.

angular.module('myAppHomeCtrl', []).controller('homeCtrl', ['$scope', 'homeContent', function($scope, homeContent){

    $scope.dataset = homeContent.getContent();
    $scope.header = homeContent.getHeader();
    $scope.subheading = homeContent.getSubheader();

}]);

服务/工厂

所以您可以看到在我们称为工厂的模块中,该文件也位于此文件夹中,如下所示.

service/factory

So you can see that in the module we call a factory, this is also in this folder and looks like this.

angular.module('myAppHomeService', [])

.factory('homeContent', function(){
  return {
    getHeader: function(){
        return "Welcome Human";
    },
    getSubheader: function(){
        return "To Joe's Awesome Website";
    },
  };
});

返回index.html

因此,在索引中,我们可以像这样在<script>标记中添加所有这些模块.

Back to index.html

So back in our index we can add all of these modules in <script> tags like this.

<!-- Angular Modules -->
<script type="text/javascript" src="app/app.module.js"></script>
<script type="text/javascript" src="app/app.routes.js"></script>
<script type="text/javascript" src="app/components/home/homeCtrl.js"></script>
<script type="text/javascript" src="app/components/home/homeService.js"></script>
<script type="text/javascript" src="app/shared/navigation-bar/navbarDirective.js"></script>
<script type="text/javascript" src="app/shared/navigation-bar/navbarService.js"></script>
<script type="text/javascript" src="app/components/login/loginCtrl.js"></script>
<script type="text/javascript" src="app/components/login/loginService.js"></script>

在生产中,您将所有这些都最小化,但是在开发过程中,您可以像这样将它们称为alll.

In production you will minify all these but you can just call them alll like this whilst in dev.

最后,我将做一个总结,以确保您拥有使模块正常工作所需的一切

To conclude I'll do a summery to make sure you have everything you need to get your modules to work

  1. 转到您的app.js(主角度模块)并为其命名应用程序.
  2. 转到您的组件并创建新模块
  3. 转到index.html并添加链接到新模块的脚本标签
  4. 现在您可以根据需要使用控制器和所有组件

我希望对角结构的指导对您有所帮助.祝你好运

I hope this guid to angular structure helps you. Good Luck

这篇关于如何在AngularJS的单独文件中包含控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆