AngularJS重用多个控制器来构建webapp

时间:2015-06-21 20:42:26

标签: angularjs

我正在寻找的是学习构建webapp的正确方法。我已经构建了一些东西,但是我已经到了需要重用一些数据的地方,并且使用ng-controllers,它变得越来越难。

我已经知道controllers不是最佳选择,所以我尝试根据我读过的一些文章跳转到directives。但他们都没有帮助过我。

所以,让我试着描述一下。

描述

我正在构建一个dashboard,我有一些客户端(添加/编辑/ del),项目(访问一个或多个客户端),议程,配置,财务等。

我已经构建了很多东西,例如:

在主页上,我正在显示一个表格,其中最后5个客户端已添加到app,还有一个表格,其中最后5个项目已添加到应用程序中。然后,在clients.html页面上,我在project.html上显示整个表格,同样适用于项目。两者都有3-4个字段,包括姓名,电话和电子邮件。然后在单个客户端页面上,我显示有关该客户端的全部信息。如地址,电子邮件,联系人,观察等。还有他参与的项目清单。

所以我拥有的是这样的:

app.js

myApp.controller('ClientesCtrl', function ($scope, $http, $routeParams) {
    $scope.pagename = "Clientes";

    $scope.get_cliente = function() { //Function - Get Cliente
        $http.get("scripts/data/clientes.json")
        .success( function(data) {
            $scope.pagedClientes = data;
        })
        .error(function(data) {});
    };

    $scope.add_cliente = function() { //Function - Add Cliente
        $scope.formprevent = true;
        $http.post('scripts/php/db.php?action=add_cliente',
            {
                'cod': $scope.cad.cod,
                [... more data ...]
            }
        )
        .success(function (data, status, headers, config) {})
        .error(function (data, status, headers, config) {});
    };
});

同样适用于项目,每个项目都有它的控制器。

我的文件夹/文件组织非常简单(因为我不知道我可以放在不同的文件中,甚至如何调用它)。它是这样的:

- 的的index.html
- 的脚本
- 的 JS
--- angular.min.js
--- 角route.min.js
- 的 应用
--- app.js
- 内容
- home.html的
- clients.html
- projects.html

问题

当我需要在很多页面中显示这些数据时,问题就出现了。
例如,在主页中,我有一个包含主要数据简历的列表,例如总客户端,项目总数,它是这样的:

<div class="col-md-3" ng-controller="ClientesCtrl">
    <div ng-init="get_cliente();>
        <div class="label">{{pagedClientes.length || "00"}}</div>
        <div class="text">clientes totais</div>
    </div>
</div>
<div class="col-md-3" ng-controller="ProjectsCtrl">
    <div ng-init="get_projects()">
        <div class="label">{{pagedProjects.length || "00"}}</div>
        <div class="text">Processos totais</div>
    </div>
</div>
<div class="col-md-3">
    <div>
        <div class="label">00</div>
        <div class="text">Processos abertos</div>
    </div>
</div>
<div class="col-md-3">
    <div>
        <div class="label">00</div>
        <div class="text">Compromissos abertos</div>
    </div>
</div>

<div class="table-body" ng-controller="ClientesCtrl">
    <table ng-init="get_clients()">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Options</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="client in pagedClients | limitTo:-5 | orderBy:'-id'" ng-if="pagedClients.length > 0">
                <td>{{cliente.cod}}</td>
                <td>{{cliente.nm_client}}</td>
                <td>
                    <a class="bt-t bt-inf" href="#/detcliente/{{cliente.id}}"></a>
                </td>
            </tr>
            <tr ng-if="pagedClientes.length == 0">
                <td colspan="3"><h3>No client</h3></td>
            </tr>
        </tbody>
    </table>
</div>

<div class="table-body" ng-controller="ProjectsCtrl">
    <table ng-init="get_projects()">
        <thead>
            <tr>
                <th>ID</th>
                <th>Project</th>
                <th>Options</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="project in pagedProjects | limitTo:-5 | orderBy:'-id'" ng-if="pagedProjects.length > 0">
                <td>{{project.cod}}</td>
                <td>{{project.nm_cliente}}</td>
                <td>
                    <a class="bt-t bt-inf" href="#/detproject/{{project.id}}"></a>
                </td>
            </tr>
            <tr ng-if="pagedClientes.length == 0">
                <td colspan="3"><h3>No project</h3></td>
            </tr>
        </tbody>
    </table>
</div>

所以,基本上,我需要在显示数据所需的每个块中添加controller,我还必须'init'函数再次获取数据。这是一个简单的例子,但我认为这足以说明我需要解决的问题。

当我需要向他们展示个人客户时,情况会更糟。所以在我对所有这些控制器感到疯狂之前,我想知道如何建立逻辑,文件夹/文件组织,代码组织的最佳方式。使用指令更好吗?使指令调用一个控制器?调用多个控制器?或者是什么?

2 个答案:

答案 0 :(得分:2)

您需要使用服务来获取数据:https://docs.angularjs.org/guide/services。对于您的代码,它看起来像这样:

    app.factory('clients', function ($http) {

        var getClients = function() { //Function - Get Cliente
            return $http.get("scripts/data/clientes.json")
            .success( function(data) {
                return data;
            })
            .error(function(data) {});
        };

        var add_cliente = function(cad) { //Function - Add Cliente
            $http.post('scripts/php/db.php?action=add_cliente',
                {
                    'cod': cad.cod,
                    [... more data ...]
                }
            )
            .success(function (data, status, headers, config) {})
            .error(function (data, status, headers, config) {});
        };

        return {
            getClients: getClients,
            add_cliente: add_cliente
        }

}) 

然后,您可以在控制器中注入服务并使用控制器中的功能:

    app.controller('Ctrl', function (clients, $scope) {
        clients.getClients().then(function (data) {
        $scope.myClients = data;
        });
    });

答案 1 :(得分:0)

在控制器初始化时阅读客户端数据 - 无需使用ng-init

myApp.controller('ClientesCtrl', function ($scope, $http, $routeParams) {
    $scope.pagename = "Clientes";

    $http.get("scripts/data/clientes.json")
        .success( function(data) {
            $scope.pagedClientes = data;
        })
        .error(function(data) {});

    $scope.add_cliente = function() { //Function - Add Cliente
        $scope.formprevent = true;
        $http.post('scripts/php/db.php?action=add_cliente',
            {
                'cod': $scope.cad.cod,
                [... more data ...]
            }
        )
        .success(function (data, status, headers, config) {})
        .error(function (data, status, headers, config) {});
    };
});

控制器可以嵌套。在div上定义控制器,该div包含您需要客户端数据的区域。与ProjectsController相同。您甚至可以合并 2个控制器。

<div ng-controller="ClientesCtrl">
    <div class="col-md-3" >
        <div ng-init="get_cliente();>
            <div class="label">{{pagedClientes.length || "00"}}</div>
            <div class="text">clientes totais</div>
        </div>
    </div>
    ....