2015-09-27 63 views
1

我写了一个简单的Angular指令,通过这个指令我在文本框中输入任何内容,例如ion-Md-input应该在我的指令中验证长度为6.并且我试图观察变量,直到它达到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); 
    } 
} 
} 
}]); 

现在,即使是在我开始在文本框中键入名称。我得到一个未定义的,仍然是这样。现在我想看到这个价值并验证它。我会怎么做呢? 经过大量SO帖子后我没有看到任何错误。

+0

你的指令不看起来那么简单。你能描述一下你想达到的目标吗?对ngModel控制器的引用是对'ionMdInput'指令的声明元素的引用 - 而不是模板中声明的ngModel。 - 你在哪里定义了一个名为link的“属性”?只有一个“链接”值。 – Michael

+0

@Michael刚刚更新了这个问题。 –

回答

3

首先你没有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

+0

很酷的东西..但'模型'观察者只会在'$ modelValue'在长度达到'6'时被填满' –

+0

我写了同样的[plunk](http://plnkr.co/edit/0S8tJoQjsr29VTzv4LCR ?p =预览)和你一样。这样我才能理解它的实质。但它不起作用。你能检查吗? –

+0

请注意,您在指令模板中具有未关闭的类属性。所以有效的你没有ngModel。 – dfsq