简体   繁体   中英

Binding data from view to controller in AngularJS

Hello I am building an angular application and I have a problem inside my stripe form. Basically I send data such as card number, expiry date and CVC code from the view to the controller's stripe callback, but I would like to add also the amount of money to pay. So I added this into my form:

<form stripe-form="handleStripe" name="myForm">
    <!-- input added for the price -->
    <div class="row" ng-if="!unregistered_user">
        <div class="input-field col col-xs-12">
            <label for="name">Amount </label>
            <input name='price' type="number" id="amount" ng-model="price">
        </div>
    </div>
<!-- credit/debit card form -->
    <div class="row">
        <div class="input-field col col-xs-12">
            <label for="cardn">Card number</label>
            <input type="text" name="number" id="cardn"  ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="myForm.number.$card.type"/>
        </div>
    </div>
    <div class="row">
        <div class="input-field col-xs-6">
            <label for="exp">Expiry</label>
            <input type="text" id="exp" ng-model="expiry" payments-validate="expiry" payments-format="expiry" />
        </div>
        <div class="input-field col-xs-6">
            <label for="cvc">CVC</label>
            <input type="text" id="cvc" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type"/>
        </div>
    </div>
    <div class="row">
        <div class="input-field col-xs-12">
            <button type="submit" class="btn btn-primary btn-large">Pay {{ price }}</button>
        </div>
   </div>
</form>

In the controller I have this variable:

▸   $scope.price = 0;

When I first load the page I can see that the price input has exactly the same amount that I put in the variable $scope.price. But when I changed it in the page and submit the form, $scope.price is always 0. It's like the data is being passed from the controller to the view, but not the way back from the view to the controller.

How can I solve this?

I think your issue is with ng-if that wraps your input with price model. ng-if creates its own scope and in your case the price is connected with the scope inside ng-if and not with you controller. You could use ng-show instead, or set the model like this: ng-model = "$parent.price" or use controllerAs syntax and you don't have to worry about this issue anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM