Joe82 Joe82 - 1 year ago 66
AngularJS Question

AngularJS - update scope when another scope value meets a greater than condition

I have an app where I get a shopping cart subtotal and then add the shipping costs to have the total. First I select the quantity of items via a select ng-option that outputs the final price

of the items

<select ng-options="item.totalprice as item.quantity for item in inventory" ng-model="subTotal"></select>

<p>Subtotal: {{subTotal}}$</p><br><br>

And then the shipping costs
are selected via ng-options

<select ng-options="country.shipping as for country in countries" ng-model="shippingCosts"></select> {{shippingCosts}}$<br><br>

Being the total the sum of both outputs:

<p>Total: {{subTotal + shippingCosts}}</p>

What I want to achieve is to set
equal to zero when
subTotal > 500
. Here you can see a working plunkr Thanks in advance!

*I tried making a variable
that would update when
subTotal > 500
, but it doesn't seem to work

if ($scope.subTotal >= 500) {
$scope.shippingFinal = 0
} else{
$scope.shippingFinal = $scope.shippingCosts

Answer Source

Use ng-change for price select. View:

<select ng-options="item.totalprice as item.quantity for item in inventory" ng-model="finalPrice" ng-change="adjustShippingCost()"></select>

In controller this might look like:

$scope.adjustShippingCost = function() {
  $scope.shippingCosts = $scope.finalPrice >= 500 ? 0 : $scope.shippingCosts;

Note that this will change the shippingCosts in one direction, i.e. you can still select them from the list. Solution here is to add ng-change for shipping, or disable, hide, etc the shipping select field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download