2016-08-04 1 views
0

데이터를 제출 한 다음 배열에 추가 한 다음 테이블에 표시합니다. 입력 텍스트 필드를 변경하면 테이블에 diretly 반영됩니다. 이 the input fields in here are directly changing the data value that has been added using the form, see the same values in last three rows양식에서 이미 제출 한 데이터의 값을 변경하는 입력 필드?

HTML

<body ng-app="crud"> 
    <div ng-controller="ctrl"> 
    <form ng-submit="sub()"> 
     <label for="name">name</label> 
     <input type="text" name="name" ng-model="myForm.name" /> 
     <br><br> 
     <label for="contact">contact</label> 
     <input type="text" name="contact" ng-model="myForm.contact" /> 
     <input type="submit" value="sumit" ng-click="sub" /> 
    </form> 
    <div> 
     <table> 
     <tr ng-repeat="x in data track by $index"> 
      <td>{{x.name}}</td> 
      <td>{{x.contact}}</td> 
      <td> 
      <button type="button" ng-click="edit(x)">Edit!</button> 
      </td> 
     </tr> 
     </table> 
    </div> 
    </div> 
</body> 

JS

var app = angular.module("crud", []); 

app.controller("ctrl", ['$scope', function($scope) { 
    $scope.data = [{ 
    name: "ankur", 
    contact: 987898 
    }, { 
    name: "santosh", 
    contact: 987678 
    }, { 
    name: "tanvi", 
    contact: 98789877 
    }]; 
    $scope.count = 0; 
    $scope.myForm = {}; 
    $scope.myForm.contact = 0; 
    $scope.myForm.name = ""; 
    $scope.sub = function(myForm) { 
    $scope.data.push($scope.myForm); 
    }; 
}]); 

답변

2

AngularJS와 같은

객체 지향적이다. 동일한 개체를 배열에 밀어 넣는 대신 복사하여 밀어 넣으십시오. 그게 널 위해 할거야.

$scope.sub = function(myForm) { 
    $scope.data.push(myForm); 
    }; 
+1

JS에

$scope.data.push(angular.copy($scope.myForm)); 

다른 방법

<form> <label for="name">name</label> <input type="text" name="name" ng-model="myForm.name" /> <br><br> <label for="contact">contact</label> <input type="text" name="contact" ng-model="myForm.contact" /> <input type="button" value="submit" ng-click="sub(myForm)" /> </form> 

나 폼 값을 추가해야 다른 방법이있다. 그것은 단지 최선의 방법으로 보이지 않는다. ( –

+1

왜 이것이 최선의 방법이 아닌지 이해할 수 없다. 배열의 항목을 푸시하는 다른 방법은 무엇이겠습니까? –

+0

개발을 위해 노력 중입니다. 각도로 간단한 CRUD. 복사를하는 것은 나중을 위해 복잡한 일이 될 것 같아요. –

관련 문제