2014-09-25 118 views
3

我有我的输入使用属性指令= text标签像这样空:

<input type="text" ng-model="helo" my-directive /> 

在我的指导,我尝试使用ngModelController保存初始我的输入的值,在这种情况下是与其相关的ng模型的值。

该指令是这样的:

app.directive('myDirective', function() { 
    return { 
      restrict: "A", 
      scope: { 

      }, 
      require: "ngModel", 
      link: function (scope, elm, attr, ngModel) { 
       console.log("hi"); 
       console.log(ngModel.$modelValue); 
       console.log(ngModel.$viewValue); 
       console.log(elm.val()); 
      } 
    } 
}); 

的问题是,ngModel $ modelValue是空的,也许是因为当时的指令被初始化ngModel尚未更新为正确的值。那么,如何在我的指令中存储在我的输入字段上设置的第一个值?

如何正确访问ngModel $ modelValue以便它具有正确的值?

我还想知道为什么这不起作用的解释,因为我没有清楚地从阅读文档中理解这一点。

Plunkr完整的例子:http://plnkr.co/edit/QgRieF

+0

大概是这个样子? http://plnkr.co/edit/R0irbC?p=preview – PSL 2014-09-25 01:08:39

回答

3

使用$watch在myDirective

app.directive('myDirective', function() { 
    return { 
     restrict: "A", 
     scope: { 

     }, 
     require: "ngModel", 
     link: function (scope, elm, attr, ngModel) { 

      var mywatch = scope.$watch(function(){ 
      return ngModel.$viewValue; 
      }, function(value){ 
      if(value){ 
       console.log("hi"); 
       console.log(ngModel.$modelValue); 
       console.log(ngModel.$viewValue); 
       console.log(elm.val()); 
       mywatch(); 
      } 
      }); 

     } 
    } 
}); 

对于演示See This Link

相关问题