Angularjs how to conditionally check a checkbox based upon existence of repeat element in another list

14,088

Solution 1

'indexOf' can't be used to find the first matched object of an array in this way(simple demo). You should find it by searching specific and unique attribute of the object, e.g., id.

Here is my example:

HTML

<div ng-controller="myCtrl">
    <ul>
        <li ng-repeat="analysisType in analysisTypes">
            <input type="checkbox" ng-class="{'checked':isExist(analysisType.id)!=-1}" ng-checked="isExist(analysisType.id)!=-1"/>
            {{analysisType.name}}
        </li>
    </ul>
</div>

JS

angular.module("myApp",[])
.controller("myCtrl",function($scope){
    $scope.analysisTypes = [{id:1,name:"typeA"},{id:2,name:"typeB"},{id:3,name:"typeC"}];

    $scope.project = {analysisTypes:[{id:2,name:"typeB"}]};

    $scope.isExist = function(id){
        return $scope.project.analysisTypes.map(function(type){return type.id;}).indexOf(id);
    }
});

Here is the jsFiddle DEMO.

Please note: Array.prototype.map and Array.prototype.indexOf only can be used in IE9+. You need to add some polyfill if you have browser supporting concern.

Solution 2

you could use the ng-checked directive to check your input when the condition return true or just bind your input with a ng-model.

try something like that

<input type="checkbox" ng-checked="project.analysisTypes.indexOf(analysisType) != -1" />
Share:
14,088
user3681971
Author by

user3681971

Updated on June 04, 2022

Comments

  • user3681971
    user3681971 almost 2 years

    as a very new angularjs user with a cshtml page, during page load of a modal window, I am trying to check a repeating checkbox if it exists in another list. the code below is conceptual:

    <li data-ng-repeat="analysisType in analysisTypes|limitTo:12 | limitTo: -6">
        <input type="checkbox" ng-class="{'checked' : project.analysisTypes.indexOf(analysisType) != -1}" />
        {{analysisType.name}}
    </li>
    

    specifically, if analysisType is found in project.analysisTypes array, I would like to check the checkbox. I am nearly certain that it is possible, but can't figure out how.

    analysisTypes and project both exist on the $scope, so that data is available.

    or maybe the solution is to bind the checkboxes directly to project.analysisTypes, but I still need to be able to dynamically render the domain checkboxes