Jonathan Jonathan - 4 months ago 18
AngularJS Question

Comparing Two Arrays with ng-repeat

I am trying create multiple checkboxes using ng-repeat from Array1, and I'd like apply the "checked" attribute (using ng-checked) to certain ones depending if there is a match in Array2.

Here we have array1 in the controller:

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


and then array2 is from the same controller but via JSON API.

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


This is my current ng-repeat set up in the template:

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


The desire is to apply the attribute
checked
to the input if, say, "condition1" in Array1 is found in "conditions" from Array2.




What I've tried:

1: I've tried using a filter (which I found on stackoverflow) after my controller:

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


with the ng-repeat amended slightly:

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


But that didn't work.

2: I've tried using another ng-repeat within the ng-repeat, then check it against the first one fir a match.

Example:

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


Hopefully somebody can help / point some guidance.
Thank You.

Answer

You don't really need a filter here, simple ngChecked directive could work:

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

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

where response is your data from API.

Comments