2014-07-17 102 views
1

我的雙向數據綁定使用ng-model不起作用。雙向數據綁定失敗ng-model

家長指令模板:

<div class="form-group"> 
    <label>Company Phone</label> 
    <input ng-model="formData.company_phone" type="phonenumber" class="form-control" placeholder="Company Phone"> 
</div> 

那孩子指令:

.directive('input', [function(){ 
    return: { 
     restrict: 'E', 
     require: '?ngModel',//right now this is binding to this directive scope, not a parent one 
     link: function($scope, element, attr, ngModel){ 
      if (attr.type !== 'phonenumber') { 
       return; 
      } 
     //some code to validate a phone number 
     $scope.$apply(function() { 
      //bind updated number, but I need this to reflect in the parent scope 
      $scope[attr.ngModel] = formattedNumber; 
} 
+0

一些相關的代碼,將有助於 – charlietfl

+0

@charlietfl我添加了一些代碼,我的道歉。 – Aaron

+2

如果您使用ng模型並綁定到相同的模型,那麼它們已經雙向綁定到它們各自的視圖。它應該工作OOTB。如果它不工作,試着找出ng模型是否引用同一個實例。有幾個關於爲什麼ng-model應該有'。'的帖子。在它裏面 - 這可能與此有關。 – pixelbits

回答

1

我用$parse來解決這個問題:

.directive('input', ['$parse', function($parse){ 
    return { 
     restrict: 'E', 
     require: '?ngModel', 
     link: function(scope, element, attr, ngModel){ 
      var getter = $parse(attr.ngModel); 
      var setter = getter.assign; 

      if (attr.type !== 'phonenumber') { 
       return; 
      } 
      //code that validated a phone number 

      scope.$apply(function() { 
       setter(scope, formattedNumber); 
      }); 
     } 
    } 
}]);