首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在angular js中修改和更新数据表行?

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

Stack Overflow用户
提问于 2014-10-20 14:18:12
回答 2查看 71K关注 0票数 18

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

我正在创建一个新项目。

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

如果我点击我的编辑按钮,然后显示所有字段,但我只想显示当前字段,那么我就单击来更新此字段。

我的代码在这里

Anguar

代码语言:javascript
复制
var app = angular.module('addApp', []);

app.controller('modifyCtrl', ['$scope', function($scope){
    $scope.tabelsData= [
        {'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit@rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
        {'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat@hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
        {'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab@punjab.com', '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代码为

代码语言:javascript
复制
<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>

代码语言:javascript
复制
		var app = angular.module('addApp', []);

		app.controller('modifyCtrl', ['$scope', function($scope){
			$scope.tabelsData= [
				{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit@rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
				{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat@hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
				{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab@punjab.com', '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;
			};

		}]);
代码语言:javascript
复制
table td, table th{
    
    border:solid 1px red;
    padding:5px;
}
代码语言:javascript
复制
<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>

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-20 14:33:37

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

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

2)制作一个包含这些布尔值的镜像数组。

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

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

JS:

代码语言:javascript
复制
$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:

代码语言:javascript
复制
<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>

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

票数 22
EN

Stack Overflow用户

发布于 2017-06-15 21:02:13

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

代码语言:javascript
复制
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);
  }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26459525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档