2014-09-25 43 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

相關問題