AngularJS在ng-repeat中拼接数组的最后一个对象,它删除了表单标记的属性

时间:2017-05-26 22:49:24

标签: javascript angularjs validation angularjs-ng-repeat splice

在我的AngularJS应用程序中,我使用ng-repeat来显示记录行。当用户删除数组中的最后一条记录时,它会删除表单标记上的自定义属性。这会破坏为这些属性设置的所有自定义验证。如果用户删除所有其他记录,则属性仍然完好无损。任何帮助深表感谢。请查看plunker代码。

http://plnkr.co/edit/8s5brh7Hj9cu0gdpNpxt?p=preview

 <body ng-controller="MainCtrl as vm">
<form name="vm.cptForm" role="form" ng-submit="vm.submit()" novalidate="">
  <table class="table">
    <thead>
      <tr>
        <th>ID</th>
        <th>NAME</th>
        <th>DATE OF SERVICE</th>
        <th>REMOVE</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in vm.items">
        <td>{{item.id}}</td>
        <td type = "text"                
            name="name"
            class = "form-control ng-class: 'error': vm.showErrors && !vm.cptForm.name.$valid}"
            ng-model="item.name">{{item.name}}</td>
        <td type = "text"
            name="dos"
            class = "form-control ng-class: 'error': vm.showErrors && !vm.cptForm.dos.$valid}"
            ng-model="item.dos">{{item.dos}}</td>
        <td>
          <button class="btn btn-xs btn-danger" type="button" ng-click="vm.remove(item)">Delete</button>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="row">
      <span class="error" ng-show="vm.showErrors && vm.cptForm.dos.$error.termedMember">
</form>
</body>

这是js

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

app.controller('MainCtrl', function($scope) {
  var vm = this;

  vm.cptForm = {};
  vm.items = [];
  vm.items = [
{
  "id":0,
  "name": "Jane",
  "dos":"05/05/2017"
},
 {
  "id":1,
  "name": "Janet",
  "dos":"05/05/2017"
},
 {
  "id":2,
  "name": "John",
  "dos":"05/05/2017"
},
 {
  "id":3,
  "name": "Johnathan",
  "dos":"05/05/2017"
},
 {
  "id":4,
  "name": "Joanne",
  "dos":"05/05/2017"
}
];

vm.remove = function(item){
  console.log(item);
  console.log(vm.cptForm);               //before splice vm.cptForm contains dos and name properties
  var index = vm.items.indexOf(item);
  debugger;
  vm.items.splice(index,1);      
  // console.log(vm.items);
   //console.log(vm.cptForm);        //after splice vm.cptForm no longer contains dos and name properties
vm.validate(vm.items);
};

vm.validate = function(items){
  angular.forEach(items,function(item){
      if(item.dos < getDate()){  //compared to today for code simplicity
         vm.cptForm.dos.$setValidity("termedMember", false);
      }
});
};


});

修改 我尝试在拼接之前创建表单的副本,然后将其分配回原始表单,但这不起作用。使用ng-repeat时,如何保留每个项目的表单属性?

0 个答案:

没有答案