18

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

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

<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>

2 Answers 2

22

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.

2) Make a mirror array that houses these booleans.

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:

$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

Sign up to request clarification or add additional context in comments.

Comments

0

Here is an example in Angular2, (this will NOT work for 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, duration: 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('duration', duration);
      params.append('main', main);
      
      //let formation = new Formation(years, label, duration, 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);
  }
  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.