如果值不是整数,我有一个字段我想验证失败。还有另一个字段可以更新该字段的值,因此我需要编写一个指令,该指令将监视字段值,并在将值更改为除 int 之外的其他值时设置验证错误。
每当将“my-required”属性添加到 HTML 时,选择选项都不会加载,并且该指令显然不起作用。
问题:我该如何进行这项工作?
这是小提琴:http: //jsfiddle.net/zFeGN/2/
html:
<select ng-model="tran.type" name="tranType" ng-init="tran.type='1'" ng-options="obj.value as obj.text for obj in tradeTypeOptions" my-required="tran.type"></select>
指示:
.directive('myRequired', function() {
  var regex = /^\-?\d*$/;
  return {
    restrict: 'A',      
    scope: {
      'myRequired': '='
    },
    link: function(scope, elm, attrs, ctrl) {     
      scope.$watch('myRequired', function(n, o){
        //alert(n);
        if (regex.test(n)) {
          ctrl.$setValidity('myRequired', true);
        } else {
          ctrl.$setValidity('myRequired', false);
        }
      },true);
    }
  };
});