2017-02-14 10 views
2

Я создал сетку с использованием данных в формате AngularJS и добавил еще две кнопки «редактировать» и «удалять» в последнем столбце.Как создать кнопку «Назад» в форме редактирования для данных в формате 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" 
    }; 
}]) 

Мои сомнения как создать кнопку, чтобы вернуться к сетке после aditing данных тха от директива, которая отображается на той же странице, что и сетка?

Как выглядит директива формы?

enter image description here

При нажатии на кнопку изменить функцию editarProjeto() вызывается и делает директиву DOM с помощью .html() метод:

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

Теперь, что такое подход, чтобы добавить кнопку «вернуться к сетке» в форме, чтобы сетка сохраняла свою опоздание st state (когда пользователь использует фильтр и вызывает форму редактирования, он/она найдет форму так же, как она была оставлена ​​до вызова формы редактирования, когда он/она нажимает кнопку «назад» **? **

Извините, если у вас возникнут вопросы при возникновении ошибки. Если вы занимите этот вопрос, пожалуйста, сообщите мне, почему, поэтому я могу исправить проблемы.

+1

Где в '$ ("# статья рендер-формы")' в HTML? Нажимает ли «Изменить» на новый URL? или это всплывающая или модальная форма? –

+1

'.html' заменяет содержимое текущей страницы, поэтому технически вы не можете вернуться в точное состояние. Возможно, вы захотите перейти к НОВЕЙШЕЙ СТРАНИЦЕ РЕДАКТИРОВАНИЯ и загрузить детали, чтобы у вас было состояние, чтобы вернуться к нему. Возможно, вам нужно настроить [ui-router] (https://ui-router.github.io/ng1/ tutorial/helloworld) – Searching

+0

@Brian Glaz Извините! Элемент, на который вы ссылаетесь, является родительским элементом таблицы. Таким образом, .HTML заменяет таблицу на форму, как @ Поиск. Я уже использую ui-router. –

ответ

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 

    }; 
}); 

 Смежные вопросы

  • Нет связанных вопросов^_^