2014-07-17 3 views
1

ng-model을 사용한 양방향 데이터 바인딩이 작동하지 않습니다. ng-model에서 양방향 데이터 바인딩이 실패 함

  • Relevant Question
  • 부모 지시어 템플릿 :

    <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-model을 사용하고 동일한 모델에 바인딩하는 경우 이미 해당 뷰에 대한 양방향 바인딩입니다. 그것은 OOTB에서 일해야합니다. 작동하지 않는 경우 ng 모델이 동일한 인스턴스를 참조하는지 확인하십시오. 왜 ng-model에는 '.'이 있어야하는지에 대한 여러 게시물이 있습니다. 여기에는 관련성이있을 수 있습니다. – pixelbits

    답변

    1

    내가사용이 문제를 해결하려면

    .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); 
          }); 
         } 
        } 
    }]); 
    
    관련 문제