0

plunker の例のようなディレクティブ テンプレート内で ui-validate を使用することは可能ですか?

プランカー: http://plnkr.co/edit/H6v6nVobIM3EKmAVHZHa?p=preview

template.html

<div class="form-group" ng-class="{'has-error' : !isValid()}">
  <label for="{{name}}" class="control-label">{{label}}</label>
  <div class="input-group">
    <span class="input-group-addon">US$</span>
    <input type="number" 
      ng-model="ngModel" 
      ng-required="isRequired" 
      ui-validate="'$value > 0'" 
      class="form-control" 
      name="{{name}}" 
      id="{{name}}" 
    />
  </div>
</div>

script.js

.directive('currency', function() {
  return {
    restrict    : 'E',
    replace     : true,
    transclude  : true,
    require     : 'ngModel',
    scope       : { ngModel: '=' },
    templateUrl : 'template.html',
    link        : function(scope, elm, attr, ctrl) {

      scope.name = (attr.name || 'undefinedName');
      scope.label = (attr.label || 'undefinedLabel');
      scope.isRequired = (attr.required !== undefined);

      scope.isValid = function() {
        return ctrl.$valid;
      };
    }
  };
});

使用法:

<currency ng-model="foo.value" name="value" label="Value:" required></currency>
4

1 に答える 1

3

サンダー・エリアス:

ngModel は非常に強力ですが、その周囲にも非常にうるさいです。トランスクルードとアイソレート スコープにより、ngModel はそれ自体をフォームに登録しません。ただし、ui-validate の場合は、ng-controller 自体を取得するだけで十分です。

基本的に解決するには、ディレクティブから削除するだけです:

require : 'ngModel'

そして、作ります:

var ctrl = elm.find('input').data('$ngModelController');

完全な議論は次の場所で見ることができます:

https://groups.google.com/forum/#!topic/angular/cMgxWTM-j00

于 2014-02-14T13:44:58.810 に答える