beingalex beingalex - 6 months ago 9
AngularJS Question

The angular way to handle this condition

I would like to display a Bootstrap modal if a certain value is empty or non-existent. The first solution I have is by passing the value to checkbox function:

// The object of functionality is to activate a
// Bootstrap modal when the checkbox is checked,
// but only if **{{part.ordered_from}}** is **empty**.

// OPTION 1 (Pass ordered_from into function):

<ul ng-repeat="part in partstoorder">

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

</ul>

<script>

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

if (ordered_from && ordered_from != '') {


$('#myModal').modal('show');

}

};

</script>


The second option I have is to add an ID to the checkbox and a data attribute so I can locate the checkbox in the dom and get the value:

// OPTION 2 (find the value of a data-ordered_from property):

<ul ng-repeat="part in partstoorder">

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

</ul>

<script>

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

var orderedFrom = $('.ordered-from-checkbox-' + id).attr('data-ordered_from');

if (orderedFrom && orderedFrom != '') {

$('#myModal').modal('show');

}

};

</script>


I am not happy with either of these solutions because I am sure the functionality could be achieved more elegantly using Angular. Any help is appreciated

Max Max
Answer

Your first option is OK btw. I would like to improve your condition

<ul ng-repeat="part in partstoorder">
    <li>{{part.ordered_from}}</li>
    <li><input type="checkbox" ng-change="change(ordered, {{part.id}}, {{part.vehicle_id}}, {{part.ordered_from}})"
        ng-true-value="1" ng-false-value="0" ng-model="ordered" name="part-ordered" >
    <li>
</ul>

<script>
$scope.change = function(value, id, vehicle_id, ordered_from) {
    if (!angular.isDefined(ordered_from)) {
        $('#myModal').modal('show');
    }
};
</script>