2

外部スコープから渡されたカスタム関数を使用して検証する入力フィールドのディレクティブを作成しようとしています。たとえば、次のようになります。

HTML:

<input type="text" custom-validator="checkValidity"/>

コントローラ:

$scope.checkValidity = function(value){
    return $scope.invalidWords.indexOf(value) === -1;
}

このための詳細なプランカーを作成しました: http://plnkr.co/edit/H5A5O3?p=preview

検証は機能しますが、デフォルトのディレクティブではうまくいかないようです。この場合、ng-disabled は機能せず、ng-model で使用される変数にアクセスできません!

これは私の指示です:

app.directive('customValidator', function() {   
   return {
      require: "ngModel"
    , scope: { customValidator: '='}
    , link: function postLink(scope, elm, attrs, ctrl) {
          var validator = function(value) {
            if(scope.customValidator && scope.customValidator(value)) {
              ctrl.$setValidity('custom-validator', true);
              return value;
            }
            ctrl.$setValidity('custom-validator', false);
            return undefined;
          }
          ctrl.$parsers.unshift(validator);
          ctrl.$formatters.unshift(validator);
        }      
   } 
});

何が問題なのかわかりません。本当に助けが必要です。

私はAngular 1.0.7にとどまるべきです

4

2 に答える 2

4

ng-disabled作業しない理由はinputB、ディレクティブを通じて新しいスコープを作成している ためです。

scope: { customValidator: '=' }

inputBモデルを同じスコープに保つには、次のinputAようにします。

app.directive('customValidator', function() {
    return {
        require: "ngModel", 
        scope: false, 
        link: function postLink(scope, elm, attrs, ctrl) {
            var validator = function(value) {
                customValidator = scope[attrs["customValidator"]];  
                if(customValidator(value)) {
                    ctrl.$setValidity('custom-validator', true);
                    return value;
                }
                ctrl.$setValidity('custom-validator', false);
                return undefined;
            }
            ctrl.$parsers.unshift(validator);
            ctrl.$formatters.unshift(validator);
        }   
    }
});
于 2013-08-21T08:04:15.133 に答える