2015-08-06 3 views
1

Привет Я новичок в Angularjs, и я понятия не имею, что я делаю. :) Мне нужно иметь возможность ввести номер кредитной карты в текстовое поле, а затем прокрутить, чтобы выяснить, какая именно кредитная карта используется и отображать изображение для этой кредитной карты. Пока у меня есть следующий код в моей директиве.Angularjs Итерация через массив с петлей

EDIT

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> 
+0

Вы хотите используйте element.bind? Или вы не возражаете против наблюдателей? – alexsmn

+0

@alexsmn Я не против использовать что-либо, что заставит его работать. Я работаю только с Angular как 2 недели. Я действительно потерян. – hollyquinn

ответ

2

Быстрое решение. Я сделаю это позже, если вы захотите.

Сначала добавьте свой html в шаблон шаблона, если его нет в данный момент.

Ввод в директиве Templete:

<input ng-model="cardNum"> 

Директива:

app.directive('myDirective', function() { 
    return { 
    restrict: 'E', 
    template: '<input ng-model="cardNum"></input>', 
    replace: true, 
    link: function($scope, elem, attr) { 
    $scope.$watch('cardNum', function(val){ 
     console.log($scope.cardNum) 
    }) 
    } 
}; 
}); 

Теперь вы можете заметить, что каждый раз, когда вы печатаете что-то на свой вход, console.log будет выводить значение, просто принять это значение и делай то, что хочешь.

Посмотрите here

UPDATE

Извините за ожидание.

Во-первых, вы хотите, чтобы проверить тип вашей карты, с помощью регулярных выражений выражения:

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}$/ } 
]; 

Что вам нужно сделать сейчас, чтобы проверить, если ваш вход соответствие один регулярное выражение из приведенного выше списка.

scope.$watch('cardNum', function(val){ 
    //The value of the input sits in `val` 
    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 
    } 
    }) 
}) 

выше Pice кода, наблюдает модель cardNum, $watch('cardNum') и каждый раз, когда значение cardNum изменил код внутри $watch рамки будет работать. Внутри области есть цикл forEach, который принимает каждое регулярное выражение и проверяет новое значение. Если есть соответствие, некоторой строке присваивается scope.cardType;

директива объем:

scope: { 
    cardNum: '=', 
    cardType: '=' 
}, 

cardNum, будет иметь значение входного сигнала.

cardType, будет типом вашей карты.

<input ng-model="crdNo"></input> 
<!--Notice how do you send the value of the input, and how you get the card type--> 
<my-directive card-num="crdNo" card-type="crdTy"></my-directive> 
{{crdTy}} 

Посмотрите, как это работает, here

После того, как вы получите тип вашей карты от crdTy, которая будет строка, вы можете использовать их здесь:

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> 
+0

Я не уверен, что понимаю.Я не уверен, что делать внутри цикла, чтобы проверить номера кредитных карт. – hollyquinn

+0

Я добавил свою полную директиву, чтобы вы могли видеть, что я делаю. – hollyquinn

+0

Нет проблем на ожидание. Просто спасибо, что помогли мне. Я изменил свой код в соответствии с вашим, но он все еще не работает. Вы видите, что я делаю неправильно? – hollyquinn