In my Angular 1.6.x project, I have a collection of checkboxes that store their state in a variable called selectedJobIds. This variable contains the ids of selected jobs along with their corresponding true or false values:
$scope.selectedJobIds = {
23: true,
56: true,
47: false
}
My goal is to check the checkboxes for those ids that exist in this object and have a value of true. Additionally, checkboxes should be checked even if they are not present in the object.
The current issue is that the program cannot distinguish between non-existent ids and ids with a false value. As a result, it unchecks both types.
Here are the approaches I've attempted:
- I tried implementing a ternary condition in the ng-model attribute:
However, this resulted in a syntax error.ng-model="(angular.isDefined(selectedJobIds[job.iid])?selectedJobIds[job.iid]:true)"
- I also experimented with using getter/setter functions in ng-model-options. The challenge here was passing the job id to the getter function and accessing the scope of the current element to determine its existence in the selectedJobIds variable.
HTML:
<ul class="list-unstyled filtered-trucks-ul">
<li ng-repeat="job in dType track by $index" style="vertical-align: middle;">
<input type="checkbox" name="job_id" value="{{job.iid}}"
ng-click="selectFilterJob()"
ng-model="selectedJobIds[job.iid]" />
<img src="23.png">
{{ job.rref + ' (' +job.iid+ ')' | uppercase }}
</li>
</ul>
JS:
$scope.checkedFilteredJobs = {
getterFunc: function(newName) {
console.log(newName)
// if(angular.isDefined($scope.selectedJobIds[id]))
// {
// return $scope.selectedJobIds[id];
// }
// else {
return true;
// }
}
};