2016-07-07 44 views
1

我想用Array1中的ng-repeat创建多个复选框,并且我想将“checked”属性(使用ng-checked)应用于特定的数据,具体取决于是否存在匹配数组2。用ng-repeat比较两个数组

在这里,我们在控制器阵列1:

$scope.possibleConditions = ["condition1", "condition2", "condition3", "condition4"]; 

,然后数组2是来自同一个控制器,但通过JSON API。

{ 
    "treated" : false, 
    "data" : [{ 
     "conditions" : ["condition1", "condition2"], 
    }] 
} 

这是我目前NG-重复设置的模板:

<p ng-repeat="condition in possibleConditions">      
    <input type="checkbox" id="{{condition}}" /> 
    <label for="{{condition}}"> 
     {{condition}} 
    </label>    
</p> 

的愿望是属性checked适用于输入如果说,“条件1”的数组1中找到来自Array2的“条件”。


我已经试过什么:

1:

.filter('customArray', function($filter){ 
return function(list, arrayFilter, element){ 
    if(arrayFilter){ 
     return $filter("filter")(list, function(listItem){ 
      return arrayFilter.indexOf(listItem[element]) != -1; 
     }); 
    } 
}; 

与NG-:我已经在我的控制器之后使用过滤器(这是我在计算器中)试图稍微重复修改:

<p ng-repeat="conditions in possibleConditions | customArray:profileData.data:'conditions' "> 

但这并没有奏效。

2:我试过在ng-repeat内使用另一个ng-repeat,然后检查它是否与第一个fir匹配。

例子:

<p ng-repeat="conditions in possibleConditions">      
    <input ng-repeat="condition in profileData.data[0].conditions | filter{condition == conditions}" type="checkbox" id="{{condition}}" /> 
    <label ng-repeat="condition in profileData.data[0].conditions | filter{condition == conditions}" for="{{condition}}"> 
     {{condition}} 
    </label>    
</p> 

希望有人能帮助/点一些指导。 谢谢。

回答

0

你并不真的需要一个过滤器在这里,简单ngChecked指令可以工作:

<p ng-repeat="condition in possibleConditions"> 
    <input type="checkbox" id="{{condition}}" 
     ng-checked="response.data[0].conditions.indexOf(condition) > -1" /> 
    <label for="{{condition}}"> 
    {{condition}} 
    </label> 
</p> 

演示:http://plnkr.co/edit/fDn0niCCljo5wChzYiwa?p=info

其中response是从API数据。

+0

这工作非常好!感谢你的快速回复。我会接受你的回答。 – Jonathan

+0

很高兴有用。 – dfsq