如何获取 Angular 输入指令数据以传递给控制器

How to get Angular Input Directive Data to Pass to Controller

我正在使用 angular-credit-cards 创建信用卡表格。信用卡号具有以下设置:

<!--... form stuff ...-->
<div class="form-group" ng-class="{'has-success': donationForm.ccNumber.$valid}">
  <label for="ccNumber">Credit Card Number</label>
  <div class="input-group">
    <input type="text" class="form-control" name="ccNumber" ng-model="credit_card.number" cc-number cc-eager-type/>
    <div class="input-group-addon">{{donationForm.ccNumber.$ccEagerType}}</div>
  </div>
</div>
<!--... more form stuff ...-->

提交此表单后,它会调用创建 Paypal 付款的函数。贝宝付款需要信用卡类型。 angular-credit-cards 根据 cc-number 指令所属的输入动态确定信用卡类型,并将其存储在输入的 $ccEagerType 中。但是,如何从输入中获取这些数据并将其传递给控制器​​?

我尝试了以下方法:

<input type="hidden" ng-model="credit_card.type" ng-value="donationForm.ccNumber.$ccEagerType"/>

但是 donationForm.ccNumber.$ccEagerType 没有绑定到 credit_card.type.

提前致谢。

阅读 readme.md 那个 github 项目,我们发现:

The eagerly matched type will be available as $ccEagerType on the model controller.

您可以通过表单名称和输入名称在您的父控制器中访问它:

$scope.donationForm.ccNumber.$ccEagerType

在您的例子中,ccNumber 是输入名称。 donationForm 是表单的推断名称,尽管您尚未在代码中发布它。

Ben Drucker 在他的自定义指令中需要 ngModelController ccNumber。阅读 AngularJS documentation about ngModelController 了解如何处理从指令内部修改的内容。

编辑: (来自 angular-信用卡的作者)

我建议避免使用隐藏输入。你最好明确地将值添加到你的请求主体到 PayPal,而不是隐式绑定它。

此外,您应该考虑使用 $ccType 来获得完整的卡片。 Eager typing 用于显示发行人徽标或其他 UI 功能。 $ccType 匹配完整卡号的更严格的正则表达式。有可能实现 $ccEagerType 已定义但 <input/> 无效且因此 $ccType 未定义的状态。

隐藏元素似乎有问题,ng-model 绑定不起作用。

Angular model binding didn't pass hidden field while posting a form

试试下面的代码

<input type="text" style="display: none;" ng-model="credit_card.type" 
ng-value="donationForm.ccNumber.$ccEagerType"/>

Refer this SO Answer