如何使用表单指令

时间:2017-02-14 18:32:58

标签: javascript html angularjs angularjs-directive

我使用AngularJS数据表创建了一个网格,并在最后一列中添加了另外两个“编辑”和“删除”按钮。

如何渲染网格/表?

HTML

<!-- Required CSS and JS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.6.0/plugins/bootstrap/datatables.bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.min.css">
<!-- AnglarJS, AngularJS Datatables and related plugins -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.6.0/angular-datatables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.6.0/plugins/bootstrap/angular-datatables.bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.6.0/plugins/buttons/angular-datatables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.6.0/plugins/columnfilter/angular-datatables.columnfilter.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.colVis.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.flash.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.print.min.js"></script>

<!-- Table/grid -->
<table datatable dt-options="concessoes.standardOptions" dt-columns="concessoes.standardColumns" dt-instance="concessoes.dtInstance" class="table table-condensed table-striped table-bordered table-hover" width="100%">
    <thead>
        <tr>
            <th data-hide="phone">ID</th>
            <th data-class="expand"> Processo</th>
            <th data-class="expand"> Objeto</th>
            <th data-hide="phone"><i class="fa fa-fw fa-map-marker txt-color-blue hidden-md hidden-sm hidden-xs"></i> UF</th>
            <th>Região</th>
            <th data-hide="phone,tablet"> Macrossegmento</th>
            <th data-hide="expand"> </th>
        </tr>
    </thead>
</table>

JavaScript /“ConcessoesCtrl”

var vm = this;
vm.dtInstance = {};
vm.standardOptions = DTOptionsBuilder
    // This is from where the data is coming
    .fromSource('/api/BasesDados/Concessoes/concessoes.php')
    .withOption('scrollX', '100%')
    .withDOM("<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
            "t" +
            "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>")
    .withBootstrap()
    .withButtons([
        {extend: 'colvis', text: 'Vizualização'},
        {extend: 'copy', text: 'Copiar'},
        {extend: 'print', text: 'Imprimir'},
        {extend: 'excel', text: 'MS Excel'},
        {
            text: 'Incluir projeto',
            key: '1',
            action: function (e, dt, node, config) {
                // This is the function to add a project
                $scope.adicionarProjeto();
            }
        }
    ]);

// Conlunas que serão mostradas
vm.standardColumns = [
    DTColumnBuilder.newColumn('id').notVisible(),
    DTColumnBuilder.newColumn('processo'),
    DTColumnBuilder.newColumn('objeto'),
    DTColumnBuilder.newColumn('uf'),
    DTColumnBuilder.newColumn('regiao'),
    DTColumnBuilder.newColumn('macro'),
    DTColumnBuilder.newColumn(null).withTitle('Ações').notSortable().renderWith(botoesDeAcao)
];
// Action buttons: edit and delete buttons
function botoesDeAcao(data, type, full, meta) {
    vm.projeto[data.id] = data;
    return '<button class="btn btn-info btn-xs" ng-click="editarProjeto(' + data.id + ')">' +
        '   <i class="fa fa-edit"></i>' +
        '</button>&nbsp;' +
        '<button class="btn btn-danger btn-xs" ng-click="excluirProjeto(' + data.id + ')">' +
        '   <i class="fa fa-trash-o"></i>' +
        '</button>';
}
// This is the function to edit the data
$scope.editarProjeto = function (projetoId) {
    // It calls a directive which renders the edititng form 
    var formularioDeEdicao = $compile("<div formulario-do-projeto></div>")($scope);
    $("article#render-form").html(formularioDeEdicao);
    // TODO: Editar os dados, chamar o servidor para fazer as alterações, então, dar um refresh na tabela
    vm.dtInstance.reloadData();
};

网格如何?

enter image description here

当我点击编辑按钮(蓝色)时,会调用一个指令,然后打开一个用于编辑数据的表单。

HTML模板

<form id="order-form" class="smart-form" novalidate="novalidate" enctype="multipart/form-data">
    <header>
        <button type="submit" class="btn btn-default btn-lg">
            <i class='fa fa-arrow-circle-left'></i>
        </button>
        <b class="text-warning">Concessão & PPPs</b>
    </header>

    <fieldset>
        <legend><strong>Projeto</strong></legend>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-circle"></i>
                    <input type="text" name="NomeDoPrograma" placeholder="Nome do programa" ng-model="NomeDoPrograma">
                </label>
            </section>
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-bars"></i>
                    <input type="text" name="NomeDoProcesso" placeholder="Nome do processo" ng-model="NomeDoProcesso">
                </label>
            </section>
        </div>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-bullseye"></i>
                    <input type="text" name="Objeto" placeholder="Objeto" ng-model="Objeto">
                </label>
            </section>
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-usd"></i>
                    <input type="text" name="InvestimentoEstimado" placeholder="Investimento estimado" ng-model="InvestimentoEstimado">
                </label>
            </section>
        </div>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-tree"></i>
                    <select type="text" name="Natureza" placeholder="Natureza" ng-model="Natureza">
                        <option value="">Natureza</option>
                        <option value="Concessão">Concessão</option>
                        <option value="PMI">PMI</option>
                        <option value="PPP">PPP</option>
                    </select>
                </label>
            </section>
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-circle-o"></i>
                    <select type="text" name="Esfera" placeholder="Esfera" ng-model="Esfera">
                        <option value="">Esfera</option>
                        <option valur="Estadual">Estadual</option>
                        <option value="Federal">Federal</option>
                        <option value="Municipal">Municipal</option>
                    </select>
                </label>
            </section>
        </div>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-map-marker"></i>
                    <select name="Uf" ng-model="Uf">
                        <option value="">Estado</option>
                        <option ng-repeat="estado in estados" value="{{estado}}">{{estado}}<option>
                    </select>
                </label>
            </section>
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-map-o"></i>
                    <select name="Regiao" placeholder="Região" ng-model="Regiao">
                        <option value="">Região</option>
                        <option value="Centro-oeste">Centro-oeste</option>
                        <option value="Nordeste">Nordeste</option>
                        <option value="Norte">Norte</option>
                        <option value="Sudeste">Sudeste</option>
                        <option value="Sul">Sul</option>
                    </select>
                </label>
            </section>
        </div>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-industry"></i>
                    <select name="Macrossegmento" placeholder="Macrossegmento" ng-model="Macrossegmento">
                        <option value="">Macrossegmento</option>
                        <option value="Saneamento básico">Saneamento básico</option>
                        <option value="Infraestrutura urbana">Infraestrutura urbana</option>
                        <option value="Energia">Energia</option>
                        <option value="Multissetorial">Multissetorial</option>
                        <option value="Mobilidade urbana">Mobilidade urbana</option>
                        <option value="Logística">Logística</option>
                        <option value="Construção naval">Construção naval</option>
                    </select>
                </label>
            </section>
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-life-ring"></i>
                    <input type="text" name="Modalidade" placeholder="Modalidade" ng-model="Modalidade">
                </label>
            </section>
        </div>
    </fieldset>
    <fieldset>
        <legend><strong>Edital & licitação</strong></legend>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-trophy"></i>
                    <input type="text" name="VencedorDaLicitacao" placeholder="Vencedor da licitação" ng-model="VencedorDaLicitacao">
                </label>
            </section>
        </div>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-calendar"></i>
                    <input type="text" name="PrevisaoDoEdital" placeholder="Previsão do edital" ng-model="PrevisaoDoEdital">
                </label>
            </section>
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-calendar-minus-o"></i>
                    <input type="text" name="PublicacaoDoEdital" placeholder="Publicação do edital" ng-model="PublicacaoDoEdital">
                </label>
            </section>
        </div>
    </fieldset>
    <fieldset>
        <legend><strong>Controle</strong></legend>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-link"></i>
                    <input type="text" name="LinkDoProcesso" placeholder="Link do processo" ng-model="LinkDoProcesso">
                </label>
            </section>
        </div>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-compass"></i>
                    <input type="text" name="FonteDaConsulta" placeholder="Fonte da consulta" ng-model="FonteDaConsulta">
                </label>
            </section>
        </div>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-user-circle"></i>
                    <input type="text" name="Validador" placeholder="Validador" ng-model="Validador">
                </label>
            </section>
        </div>
        <div class="row">
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-list-ul"></i>
                    <input type="text" name="SituacaoDoProcesso" placeholder="Situação do processo" ng-model="SituacaoDoProcesso">
                </label>
            </section>
            <section class="col col-6">
                <label class="input"> <i class="icon-append fa fa-certificate"></i>
                    <input type="text" name="StatusDaOperacao" placeholder="Status da operação" ng-model="StatusDaOperacao">
                </label>
            </section>
        </div>
        <section>
            <label class="checkbox">
                <input type="checkbox" name="Validacao" ng-model="Validacao">
                <i></i>Validar as informações acima</label>
        </section>
    </fieldset>
    <fieldset>
        <legend><strong>Anexos</strong></legend>
        <section>
            <div class="input input-file">
                <span class="button">
                    <input type="file" name="Arquivo" onchange="this.parentNode.nextSibling.value = this.value" ng-model="Arquivo">Procurar arquivos
                </span>
                <input type="text" placeholder="Incluir arquivos" readonly="">
            </div>
        </section>
    </fieldset>
    <fieldset>
        <legend>
            <strong>Histórico</strong>
        </legend>
        <section>
            <label class="textarea"> <i class="icon-append fa fa-history"></i>
                <textarea rows="5" name="Observacoes" placeholder="Observações sobre o projeto e outras informaçoes importantes" ng-model="Observacoes"></textarea>
            </label>
        </section>
    </fieldset>
    <footer>
        <button type="submit" class="btn btn-danger">
            Excluir projeto <i class='fa fa-trash'></i>
        </button>
        <button type="submit" class="btn btn-default">
            Cancelar <i class='fa fa-times'></i>
        </button>
        <button type="submit" class="btn btn-default">
            Salvar & Voltar <i class='fa fa-save'></i>
        </button>
        <button type="submit" class="btn btn-primary" ng-click="salvarProjeto()">
            Salvar <i class="fa fa-send-o"></i>
        </button>
    </footer>
</form>

JavaScript /“formularioDoProjeto”

.directive('formularioDoProjeto', ['FormData', function (FormData) {
    return {
        restrict: "AE",
        templateUrl: "app/database/concessoes/formulario-do-projeto.html"
    };
}])

我怀疑如何在从与网格相同的页面中呈现的指令中添加数据之后创建一个返回网格的按钮?

表单指令是什么样的?

enter image description here

当我单击编辑按钮时,会调用函数 editarProjeto() ,并使用 .html()将指令呈现给DOM 方法:

$scope.editarProjeto = function (projetoId) {
    var formularioDeInclusao = $compile("<div formulario-do-projeto></div>")($scope);
    $("article#render-form").html(formularioDeInclusao);
    //vm.dtInstance.reloadData();
};

现在,在表单中添加“返回网格”按钮的方法是什么,以便网格保持其最新状态(当用户使用过滤器并调用编辑表单时,当他/她按下“后退”按钮时,她/他会在调用编辑表单之前找到与表单相同的方式**?**

对于提问时的任何错误,我们深表歉意。如果您对这个问题进行了投票,请告诉我原因,以便我能纠正这些问题。

1 个答案:

答案 0 :(得分:1)

找到解决方案:

HTML

<table ng-show="!editing">...</table>

<project-form ng-hide="!editing"></project-form>

的JavaScript

.controller('ProjectCtrl', function($scope){
    // It starts as false so the grid/table is shown first
    $scope.editing = false;
    $scope.backToGrid = function(){
        $scope.editing = false;
    };

    // When I want to edit the project I set the $scope.editing to true, so the form is shown
    $scope.editProject = function(projectId){
        $scope.editing = true;
        // The rest of the steps goes here

    };
});