如何在隔离指令中查看输入有效性

时间:2014-09-05 21:11:20

标签: angularjs angularjs-directive angularjs-scope

我正在尝试从自定义指令中观察输入元素的有效性,但是我遇到了问题。我创建了以下简单应用

var app = angular.module('plunker', []);

app.directive('test', [function(){
  return {
    restrict: 'E',
    scope: {
      coordinate: '=ngModel',
      field: '='
    },
    require: 'ngModel',
    templateUrl:'test.tpl.html',
    link:function(scope, element, attrs, ngModel){
      scope.amount = 1;
      scope.valid = true;

      scope.$watch(function(){
        return ngModel.$valid;
      }, function(value){
        scope.valid = value;
        console.log('Our ngModel is ' + value);
      });
      scope.$watch(function(){
        return scope.field.$valid;
      }, function(value){
        scope.valid = value;
        console.log('Field is valid ' + value);
      });
    }
  };
}]);

其中test.tpl.html定义为

<input class="form-control" type="text" required="required" name="fruit" ng-model="fruit" />
<select class="form-control" ng-model="amount" ng-disabled="!valid">
    <option value="1" selected="selected">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

并使用

将它拉到一起
<body>
  <form name="testForm" novalidate>
    <div class="form-group" ng-class="{ 'has-error' : testForm.fruit.$invalid && !testForm.fruit.$pristine}">
      <test ng-model="fruit" field="testForm.fruit"></test>
    </div>
  </form>
</body>

但是,我可以获得验证更改通知的唯一方法是使用现场监视,而不是坐标。需要做些什么才能让我不必通过现场观察有效性?

附件是说明问题的傻瓜

http://plnkr.co/edit/cIiv2PNc6te42lMshxJE?p=preview

0 个答案:

没有答案