2017-10-19 58 views
0

我有一个可观察数组(通过ajax填充)验证时,不能在数组中的任何2个或多个观察值上具有相同的选择值。验证ObservableArrays之间的重复数据

<div id="AttrValidationDiv"></div> 
    <table>  
    <!-- ko foreach: AttrsViewModels --> 
     <tr> 
      <td> 
       <select data-bind="options:$root.optionsViewModel, optionsText:'ProductName', optionsValue:'ProductId',value:ServiceGroup, optionsCaption:'Select'"></select> 
      </td> 
      </tr> 
     <!-- /ko --> 
    </table> 

有没有一种方法可以在实时添加/删除验证div中完成此操作?

回答

2

您可以使用计算函数来完成此操作,该函数根据AttrsViewModels中的选定选项检查每个选项。只要选定的选项发生变化,计算器就会自动重新计算,因为它们是可观察的,并且如果绑定到计算函数,则div文本将被更新。

function viewModel(){ 
 
    var self = this; 
 
    
 
    this.optionsViewModel = [ 
 
    { ProductId: 1, ProductName: 'product 1' }, 
 
    { ProductId: 2, ProductName: 'product 2' }, 
 
    { ProductId: 3, ProductName: 'product 3' } 
 
    ]; 
 
    
 
    this.AttrsViewModels = ko.observableArray([ 
 
    { ServiceGroup: ko.observable() }, 
 
    { ServiceGroup: ko.observable() }, 
 
    { ServiceGroup: ko.observable() } 
 
    ]); 
 
    
 
    this.validations = ko.computed(function(){ 
 
    for(var i=0; i<self.optionsViewModel.length; i++){ 
 
    \t var option = self.optionsViewModel[i]; 
 
     var matches = self.AttrsViewModels().filter(function(item){ 
 
      return item.ServiceGroup() === option.ProductId; 
 
     }); 
 
     if(matches.length >= 2){ 
 
     \t  return option.ProductName + ' is selected more than once'; 
 
     } 
 
    } 
 
    return ''; 
 
    }); 
 
} 
 
    
 
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="AttrValidationDiv"> 
 
    <span data-bind="text: validations"></span> 
 
</div> 
 
<table>  
 
    <tbody> 
 
    <!--ko foreach: AttrsViewModels--> 
 
    <tr> 
 
     <td> 
 
      <select data-bind="options:$root.optionsViewModel, optionsText:'ProductName', optionsValue:'ProductId',value:ServiceGroup, optionsCaption:'Select'"></select> 
 
     </td> 
 
    </tr> 
 
    <!--/ko--> 
 
    </tbody> 
 
</table>

+0

谢谢。正是我需要的。 – Mildfire

+0

我想知道是否有可能在AttrsViewModels中引入“Level”属性。例如:“'级别为1的服务组已经被选定为2,3级。” – Mildfire

+0

@Mildfire我不确定你的结构是什么样子,但我不明白为什么不。如果你可以把一个jsFiddle与更多的代码放在一起,我会看看。 –