【发布时间】:2015-08-06 13:14:38
【问题描述】:
您好,我是 Angularjs 的新手,我不知道自己在做什么。 :) 我需要能够在文本框中输入信用卡号,然后遍历以找出正在使用的信用卡类型并显示该信用卡的图像。到目前为止,我的指令中有以下代码。
编辑
app.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
cardNum: '=',
cardType: '='
},
template: '<input ng-model="cardNum"></input>',
replace: true,
link: function ($scope, elem, attr) {
scope.$watch('cardNum', function (val) {
var regMap = [
{ id: 'visa', reg: '^4[0-9]{12}(?:[0-9]{3})?$' },
{ id: 'mastercard', reg: '^5[1-5][0-9]{14}$' },
{ id: 'discover', reg: '^6(?:011|5[0-9]{2})[0-9]{12}$' },
{ id: 'amex', reg: '^3[47][0-9]{13}$' }
];
angular.forEach(regMap, function(e){
//The current element of the regMap sits in e which is an object `{id:, :reg}`
if(e.reg.test(val)) {
//In the above if you test if the val(which is the input value) is matching the regex `e.reg` and if there is a match you pass the id of the object to a scope variable which was sent into the directive.
scope.cardType = e.id
}
})
})
}
};
});
<div class="form-group">
<div class="row">
<div class="col-lg-8">
<label for="CCnum" class="control-label">{{ 'CC_NUMBER' | translate }}</label>
<input id="CCnum" name="CCnum" class="form-control" title="Number on the front of your card" required="" type="text" ng-model="crdNo">
<!--ve-credit-card-no="vm.ccType"-->
<ve-credit-cardno card-num="crdNo" card-type="crdTy"></ve-credit-cardno>
{{crdTy}}
<div class="error_msg" ng-show="ccform.CCnum.$error.required && submit">Please enter a credit card number</div>
</div>
<div class="col-lg-3">
<label for="ccimg" class="control-label"></label>
<span ng-show="crdTy == 'visa'">visa<img id="ccimg" class="img-responsive" src="../../Assets/img/visa.png" /></span>
<span ng-show="crdTy == 'mastercard'">mastercard<img id="ccimg" class="img-responsive" src="../../Assets/img/mastercard.png" /></span>
<span ng-show="crdTy == 'discover'">discover<img id="ccimg" class="img-responsive" src="../../Assets/img/discover.png" /></span>
<span ng-show="crdTy == 'discover'">amex<img id="ccimg" class="img-responsive" src="../../Assets/img/amex.png" /></span>
</div>
</div>
</div>
【问题讨论】:
-
你想使用 element.bind 吗?或者你不介意观察者?
-
@alexsmn 我不介意使用任何可以使它工作的东西。我只使用 Angular 2 周。我真的迷路了。
标签: javascript angularjs loops