0

我有這樣的形式:

business-validation是一個自定義的指令,其代碼爲:

var CREDIT_CARD_REGEX = /^\d{0,24}$/; 
angular.module('directives').directive('creditCard', [ 
    function() { 
     return { 
      restrict: 'A', 
      require: 'ngModel', 
      link: function (scope, element, attrs, ctrl) { 
       scope.$watch(attrs.creditCard, function (newValue) { 
        return ctrl.$setViewValue(ctrl.$viewValue); 
       }); 
       return ctrl.$parsers.push(function (viewValue) { 
        var newValue; 
        newValue = ctrl.$modelValue; 

        element.validateCreditCard(function (result) { 
         if (result.card_type && 
           result.luhn_valid && 
           result.length_valid && 
           CREDIT_CARD_REGEX.test(element.val())) { 
          element.attr("data-card-type", result.card_type.name); 
          ctrl.$setValidity('creditCard', true); 
          newValue = viewValue; 
         } 
         else { 
          element.removeAttr("data-card-type"); 
          ctrl.$setValidity('creditCard', false); 
         } 
        }, { accept: ['visa', 'mastercard'] }); 

        return newValue; 
       }); 
      } 
     }; 
    }]); 

我需要的myForm.anInputName.$error.creditCard值在控制器,併爲此我做了this attempts和也類似於:

<input type="hidden" ng-model="IsCreditCardValid" name="IsCreditCardValid" value="myForm.anInputName.$error.creditCard" /> 

$scope.$watch("IsCreditCardValid", function (newValue, oldValue) { 
    alert('theChangeHasBeen:' + oldValue + ' -> ' + newValue); 
}); 

爲了$watchIsCreditCardValid在控制器。

這一段顯示:

<p class="help-block" ng-if="smyForm.anInputName.$error.creditCard && !myForm.anInputName.$error.required">Wrong credit card number!</p> 

,但隱藏的輸入永遠不會盡管使用相同的條件下的預期值。爲什麼最後一個隱藏字段沒有更新,並且從未觸發過$watch

編輯
如果我做

myForm.anInputName.$valid: {{myForm.anInputName.$valid}}
值更新在屏幕上,但隱藏字段不會改變它的值。

+1

建議你創建一個簡單的演示(一個不需要信用卡號碼) – charlietfl

+0

@charlietfl我有急事目前我...但我會盡正如你剛纔所說... – JPCF

+0

@charlietfl我添加了一個編輯,給你任何提示? – JPCF

回答

0

ngModel僅適用於listed input types,隱藏不在其中。 input指令的內部做一個暗示,它不會在所有可能的輸入自動工作:

var inputType = { 

    ... 

    'hidden': noop, 
    'button': noop, 
    'submit': noop, 
    'reset': noop, 
    'file': noop 
} 

這是有道理的,因爲隱藏的投入並不需要雙向綁定(它們在角應用不必要,太)。如果你一定要使用它們,然後

<input type="hidden" name="IsCreditCardValid" value="{{ IsCreditCardValid }}" /> 
+0

我試過[that](http://stackoverflow.com/questions/29479977/why-is-this-hidden-field-not-updated-when-watch-is-used-on-the-controller?noredirect = 1#comment47121975_29479977)但它不起作用... – JPCF

+0

我想你除了主題還有問題,並且當你發佈單行代碼而沒有進一步的上下文時,他們似乎不可解決。 – estus

相關問題