如何在指令中观察 Angular 变量并验证?

How to watch Angular variables in a directive and Validate?

我在 Angular 中编写了一个简单的指令直到它达到大小 6 并验证并基于它激活提交按钮。

index.html

<div>          
<ion-md-input label="Enter the Device ID" hightlight-color="dark" type="text" ng-model="link" required ng-minlength=6></ion-md-input>               
</div>

指令

vehicoApp.directive('ionMdInput', ['$http',function($http){
console.log('In ionMdInput');
  return {
    restrict : 'E',
    template : 
    '<input type="text" class="transition-input ng-model="link" required ng-minlength=6>'+
    '<span class="md-highlight"></span>'+
    '<span class="md-bar"></span>'+
    '<label>{{label}}</label>', 
    require : 'ngModel',
    scope : {
      'label' : '@',
      'ngModel' : '='
    },

link : function (scope, elem, attrs, ngModel)
{
  if(!ngModel) return;

  scope.$watch(attrs.link, function(){ 
    validate();
  }, true);

  var validate = function() {
    var val1 = ngModel.$viewValue;
    console.log(val1);
  }
 }
}
}]);

现在甚至在我开始在文本框中输入名称之前。我得到一个 undefined ,它仍然像它一样。现在我想查看该值并验证它。我该怎么办? 在浏览了大量的 SO 帖子后,我没有看到任何错误。

首先你没有link属性。那么你的范围配置不是你在你的情况下的设置方式。您可以简单地将 ngModel 属性双向绑定到将用作指令输入的 ngModel 的内部范围模型。

完成这些更改后,您可以为此模型设置观察器:

scope.$watch('model', function() {
    validate();
}, true);

整个指令如下所示:

.directive('ionMdInput', ['$http', function($http) {
    return {
        restrict: 'E',
        template: 
            '<input type="text" class="transition-input" ng-model="model" required ng-minlength=6>' +
            '<span class="md-highlight"></span>' +
            '<span class="md-bar"></span>' +
            '<label>{{label}}</label>',
        scope: {
            'label': '@',
            'model': '=ngModel'
        },

        link: function(scope, elem, attrs) {
            if (!attrs.ngModel) return;

            scope.$watch('model', function() {
                validate();
            }, true);

            var validate = function() {
                console.log(scope.model);
            }
        }
    }
}]);

演示: http://plnkr.co/edit/wh8ylLbW4YpZcEKOryae?p=preview