Javascript 如何在angular js中修改和更新数据表行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26459525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:55:30  来源:igfitidea点击:

How to modify and update data table row in angular js?

javascriptangularjs

提问by Rohit Azad

I m learning of angular js and i have found i issue .

我正在学习 angular js,我发现我有问题。

I m creating a new projects .

我正在创建一个新项目。

i have some button edit , add, remove,

我有一些按钮编辑,添加,删除,

if i click to my edit button than show all field but i want to show only current field than i click to update update this filed .

如果我单击我的编辑按钮而不是显示所有字段,但我只想显示当前字段而不是单击更新此字段。

My code is here

我的代码在这里

Anguar

安瓜尔

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

app.controller('modifyCtrl', ['$scope', function($scope){
    $scope.tabelsData= [
        {'name':'rohit', 'dob':'15-august-1985', 'emailId':'[email protected]', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
        {'name':'aman', 'dob':'26-july-1975', 'emailId':'[email protected]', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
        {'name':'devraj', 'dob':'27-march-1980', 'emailId':'[email protected]', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
    ];


    $scope.modify = function(tableData){

        $scope.modifyField = true;
        $scope.viewField = true;
    };


    $scope.update = function(tableData){
        $scope.modifyField = false;
        $scope.viewField = false;
    };

}]);

HTML Code is

HTML 代码是

<div ng-app="addApp">

<div class="wraper" ng-controller="modifyCtrl">

            <table>
                <thead>
                    <tr>
                        <th>Name:</th>
                        <th>Date Of Birth</th>
                        <th>Email Id</th>
                        <th>Phone No.</th>
                        <th>Address</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="tableData in tabelsData"><form>
                        <td>
                            <div ng-hide="viewField">{{tableData.name | uppercase}}</div>
                            <div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
                        </td>
                        <td>
                            <div ng-hide="viewField">{{tableData.dob}}</div>
                            <div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
                        </td>
                        <td>
                            <div ng-hide="viewField">{{tableData.emailId}}</div>
                            <div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
                        </td>
                        <td>
                            <div ng-hide="viewField">{{tableData.phone}}</div>
                            <div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
                        </td>
                        <td>
                            <div ng-hide="viewField">{{tableData.address}}</div>
                            <div ng-show="modifyField">
                                <textarea ng-model="tableData.address"></textarea>
                            </div>
                        </td>
                        <td>
                            <button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
                            <button ng-show="modifyField" ng-click="update(tableData)">Update</button>
                            <button ng-hide="viewField">Add</button>
                            <button ng-hide="viewField">Remove</button>
                        </td></form>
                    </tr>
                </tbody>
            </table>

        </div>

</div>

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

  app.controller('modifyCtrl', ['$scope', function($scope){
   $scope.tabelsData= [
    {'name':'rohit', 'dob':'15-august-1985', 'emailId':'[email protected]', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
    {'name':'aman', 'dob':'26-july-1975', 'emailId':'[email protected]', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
    {'name':'devraj', 'dob':'27-march-1980', 'emailId':'[email protected]', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
   ];


   $scope.modify = function(tableData){

    $scope.modifyField = true;
    $scope.viewField = true;
   };


   $scope.update = function(tableData){
    $scope.modifyField = false;
    $scope.viewField = false;
   };

  }]);
  
table td, table th{
    
    border:solid 1px red;
    padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="addApp">

<div class="wraper" ng-controller="modifyCtrl">

   <table>
    <thead>
     <tr>
      <th>Name:</th>
      <th>Date Of Birth</th>
      <th>Email Id</th>
      <th>Phone No.</th>
      <th>Address</th>
      <th>Action</th>
     </tr>
    </thead>
    <tbody>
     <tr ng-repeat="tableData in tabelsData"><form>
      <td>
       <div ng-hide="viewField">{{tableData.name | uppercase}}</div>
       <div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
      </td>
      <td>
       <div ng-hide="viewField">{{tableData.dob}}</div>
       <div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
      </td>
      <td>
       <div ng-hide="viewField">{{tableData.emailId}}</div>
       <div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
      </td>
      <td>
       <div ng-hide="viewField">{{tableData.phone}}</div>
       <div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
      </td>
      <td>
       <div ng-hide="viewField">{{tableData.address}}</div>
       <div ng-show="modifyField">
        <textarea ng-model="tableData.address"></textarea>
       </div>
      </td>
      <td>
       <button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
       <button ng-show="modifyField" ng-click="update(tableData)">Update</button>
       <button ng-hide="viewField">Add</button>
       <button ng-hide="viewField">Remove</button>
      </td></form>
     </tr>
    </tbody>
   </table>

  </div>

</div>

回答by ryanlutgen

If you only want one row to show the inputs on clicking its respective modify button you have two options:

如果您只希望一行显示单击其相应修改按钮时的输入,您有两个选择:

1) Attach booleans to each of the JSON indexes of the tabelsData array.

1) 将布尔值附加到 tabelsData 数组的每个 JSON 索引。

2) Make a mirror array that houses these booleans.

2)制作一个容纳这些布尔值的镜像阵列。

Having two separate booleans in this case is useless, because each one is being treated on a toggle basis:

在这种情况下,有两个单独的布尔值是没有用的,因为每个布尔值都是在切换的基础上处理的:

Here is the core code for doing approach number two since I assume you want your data to remain the same:

这是执行方法二的核心代码,因为我假设您希望您的数据保持不变:

JS:

JS:

$scope.editingData = {};

for (var i = 0, length = $scope.tabelsData.length; i < length; i++) {
  $scope.editingData[$scope.tabelsData[i].id] = false;
}

$scope.modify = function(tableData){
    $scope.editingData[tableData.id] = true;
};


$scope.update = function(tableData){
    $scope.editingData[tableData.id] = false;
};


Html:

网址:

<tbody>
    <tr ng-repeat="tableData in tabelsData">
        <td>
            <div ng-hide="editingData[tableData.id]">{{tableData.name | uppercase}}</div>
            <div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.name" /></div>
        </td>
        <td>
            <div ng-hide="editingData[tableData.id]">{{tableData.dob}}</div>
            <div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.dob" /></div>
        </td>
        <td>
            <div ng-hide="editingData[tableData.id]">{{tableData.emailId}}</div>
            <div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.emailId" /></div>
        </td>
        <td>
            <div ng-hide="editingData[tableData.id]">{{tableData.phone}}</div>
            <div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.phone" /></div>
        </td>
        <td>
            <div ng-hide="editingData[tableData.id]">{{tableData.address}}</div>
            <div ng-show="editingData[tableData.id]">
                <textarea ng-model="tableData.address"></textarea>
            </div>
        </td>
        <td>
            <button ng-hide="editingData[tableData.id]" ng-click="modify(tableData)">Modify</button>
            <button ng-show="editingData[tableData.id]" ng-click="update(tableData)">Update</button>
            <button ng-hide="viewField">Add</button>
            <button ng-hide="viewField">Remove</button>
        </td>
    </tr>
</tbody>

I made an example: http://plnkr.co/edit/lXq1WB

我举了一个例子:http: //plnkr.co/edit/lXq1WB

回答by Redouane nomade

Here is an example in Angular2, (this will NOT work for AngularJS!)

这是Angular2 中的一个示例,(这不适用于 AngularJS!)

fichier.html:
    <ng2-toasty [position]="'top-left'"></ng2-toasty>
    <label for="trainingInput" class="mr-2">{{ 'LABEL.FORMATION' | translate }} :</label>
    <table class="table table-hover table-striped table-sortable table-bordered">
        <thead>
            <tr>
                <th *ngFor="let column of columns" [class]="selectedClass(column.variable)" (click)="changeSorting(column.variable)" translate>
                    {{column.display}}
                </th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let object of data | orderBy : convertSorting(); let rowIndex = index">
                <td *ngFor="let column of columns" class="{{column.variable}}-td">
                    <div *ngIf="!toUpdates[object['id']]" >{{object[column.variable] | format: column.filter}}</div>
                     <div *ngIf="toUpdates[object['id']]"><input type="text" [(ngModel)]="object[column.variable]" ></div>
                </td>
                <td class="text-center">
                    <i *ngIf="!toUpdates[object['id']]" class="fa fa-pencil-square-o edit-formation" aria-hidden="true" (click) = "editFormation(object)"></i>
                    <i *ngIf="toUpdates[object['id']]" class="fa fa-check-square-o save-edit-form" (click)="updateFormation(object)"></i>
                    <i class="fa fa-times" aria-hidden="true" (click)="deleteFormation(object['id'])"></i>
                </td>
            </tr>
             <tr [hidden]="isDisabled()">
                <td><input type="text" class="form-control" placeholder="Année" #years></td>
                <td><input type="text" class="form-control" placeholder="Formation" #label></td>
                <td><input type="text" class="form-control" placeholder="Durée" #duration></td>
                <td class="text-center align-middle">
                <i class="fa fa-plus-circle fa-2x" (click)="addFormation(years.value, label.value, duration.value)"></i>
                </td>
            </tr>
        </tbody>
    </table>

fichier.ts:
import {Component, Injector, Input, OnChanges, OnInit} from '@angular/core';
import { Http, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import DynamicComponent from '../dynamic-component';
import Formation from './formation';
import {ToastyService, ToastyConfig, ToastOptions, ToastData} from 'ng2-toasty';


@Component({
    moduleId: module.id,
    selector: 'formations-selector',
    templateUrl: './formations-template.html',
    styleUrls: ['./formations-template.css'],
})
export default class FormationsComponent{

    candidate: any = null;
    listFormations: any = null;
    candidateDetails: any = null;
    columns: any[];
    sort: any;
    data: any[];
    toUpdates: {};

  constructor(private injector: Injector, private http: Http,private toastyService: ToastyService, private toastyConfig: ToastyConfig) {
      this.candidateDetails = this.injector.get('candidateDetails');
      this.candidate = this.candidateDetails.candidate;
      this.listFormations = this.candidateDetails.listFormations;
      this.columns = this.listFormations.columns;
      this.sort = this.listFormations.sort;
      this.data = this.listFormations.data;
      this.toastyConfig.theme = 'material';
      this.toUpdates = {};
  } 

  ngAfterViewInit(){
      $(document).ready(function() {
          /*
          $('.edit-formation').click(function () {
              var dad = $(this).parent().parent();
              dad.find('td .duration-span').hide();
              dad.find('td.duration-td').append('<input type="text" class="form-control"  placeholder="Durée" value="'+dad.find('td .duration-span').html()+'" id = "duration-update" #durationu>');
              dad.find('td  .label-span').hide();
              dad.find('td.label-td').append('<input type="text" class="form-control" placeholder="Formation" id="label-update" value="'+dad.find('td .label-span').html()+'" #labelu>');
              dad.find('td  .years-span').hide();
              dad.find('td.years-td').append('<input type="text" class="form-control" placeholder="Année" id="years-update" value="'+dad.find('td .years-span').html()+'" #yearsu>');

              dad.find('td.years-td').append('<i class="fa fa-check-square-o save-edit-form hidden" (click)="updateFormation(1, years.value, label.value, durationu)"></i>');


              dad.find('td .edit-formation').addClass("hidden");
              dad.find('td .save-edit-form').removeClass("hidden");

          });
          */
          /*
          $('.save-edit-form').click(function () {
              var dad = $(this).parent().parent();
              dad.find('td .save-edit-form').addClass("hidden");
              dad.find('td .edit-formation ').removeClass("hidden");

              dad.find('td .duration-span').show();
              $('#duration-update').remove();
              dad.find('td .label-span').show();
              $('#label-update').remove();
              dad.find('td .years-span').show();
              $('#years-update').remove();
            });
          */
      });
}


  //Action déclenché lors d'un changement de société du candidat : on met à jour la liste des métiers associés
  onChangeCompaniesInput(value) {

  }

  isDisabled(isDisabled) {
      //return (isDisabled || !this.candidateDetails.isUserAuthorized) ? true : false;
  }

  selectedClass(columnName): string{
      return columnName == this.sort.column ? 'sort-' + this.sort.descending : '';
  }

  changeSorting(columnName): void{
      var sort = this.sort;
      if (sort.column == columnName) {
        sort.descending = !sort.descending;
      } else {
        sort.column = columnName;
        sort.descending = false;
      }
  }

  convertSorting(): string{
      return this.sort.descending ? '-' + this.sort.column : this.sort.column;
  }

  onChangeMainFormaion(value): void{
      console.log(value);
  }

  deleteFormation(idFormation): void{
      let headers      = new Headers('Content-Type', 'application/json'); 
      let params: URLSearchParams = new URLSearchParams();

      this.http.post('/api/formations/'+idFormation+'/deleteFormation', params).toPromise()
          .then(
                  res =>
                  {
                      if(res.status == 200){
                          this.toastyService.success({
                              title: "Success",
                              msg: "La formation a etait supprmié avec Succès",
                              showClose: true,
                              timeout: 5000,
                              theme: 'default',
                          });
                      }else{
                          this.toastyService.error({
                              title: "Error",
                              msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
                              showClose: true,
                              timeout: 5000,
                              theme: 'default',
                          });
                      }
                  }
                  ).catch(this.handleError);
  }

  editFormation(tableData): void{
      this.toUpdates[tableData['id']]= true;
  }

  updateFormation(tableData): void {
      this.toUpdates[tableData['id']]= false;
      console.log(tableData);
  }

  addFormation(years: string, label: string, durration: string, main: boolean = false): void{
      let headers      = new Headers('Content-Type', 'application/json'); 
      let params: URLSearchParams = new URLSearchParams();
      params.append('years', years);
      params.append('label', label);
      params.append('durration', durration);
      params.append('main', main);

      //let formation = new Formation(years, label, durration, false);
      return this.http.post('/api/formations/'+this.candidate.id+'/addFormation', params).toPromise()
          .then(
                  res =>
                  {
                      if(res.status == 200){
                          this.toastyService.success({
                              title: "Success",
                              msg: "La formation a etait ajouter avec Succès",
                              showClose: true,
                              timeout: 5000,
                              theme: 'default',
                          });
                      }else{
                          this.toastyService.error({
                              title: "Error",
                              msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
                              showClose: true,
                              timeout: 5000,
                              theme: 'default',
                          });
                      }
                  }
                  ).catch(this.handleError);
  }

  private handleError(error: any) {
      let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
      console.error(errMsg);

      return Promise.reject(errMsg);
  }

}