beingalex beingalex - 6 months ago 51
AngularJS Question

Checkbox and ng-change. Need to uncheck if condition exists

I need to be able to programmatically set a checkbox to unchecked when an event happens (the event is actually a modal being hidden). I need to keep the current

ng-change
function with the same parametes.

I have a checkbox element:

<input type="checkbox" ng-change="change(ordered, $index, {{part.id}}, {{part.vehicle_id}}, '{{part.ordered_from}}')" ng-true-value="1" ng-false-value="0" ng-model="ordered" name="part-ordered" />


And my JS:

$scope.change = function(value, part_index, id, vehicle_id, ordered_from_val) {

if (modal_hidden_event) {

// UNCHECK CODE.

}

}


I am not too sure what to search for or what area of the docs will help me.

Answer

I am not sure where modal_hidden_event is coming from, I am assuming it is just a placeholder here. I've also cleaned up your change function in the HTML, as it does not need to be interpolated, as the values exist without:

Use ng-checked:

HTML

<input type="checkbox"
    ng-change="change(ordered, $index, part.id, part.vehicle_id, part.ordered_from)"
    ng-true-value="1"
    ng-false-value="0"
    ng-model="ordered"
    ng-checked="checkedStatus"
    name="part-ordered"  />

JS

$scope.checkedStatus = true;
$scope.change = function(value,  part_index, id, vehicle_id, ordered_from_val) {

    if (modal_hidden_event) {
        $scope.checkedStatus = false;
    }

}

I also recommend just passing the part into the function, and you can grab each property there:

HTML

"change(ordered, $index, part)"

$scope.change = function(value, part_index, part) {

JS

$scope.change = function(value, part_index, part) {

    var part_id = part.id,
        vehicle_id = part.vehicle_id,
        ordered_from_val = part.ordered_from;


    if (modal_hidden_event) {
        $scope.checkedStatus = false;
    }

}