2017-01-18 3 views
0

AngularJs에 문자 구분자가있는 입력란에 입력 된 번호의 서식을 지정하고 싶습니다.ngModel이있는 사용자 정의 문자 구분 기호가 올바르게 작동하지 않습니다.

서식을 지정하라는 지시문을 만들었습니다. 지시문이 올바른 출력을 생성하고 있지만 ngModel을 올바르게 업데이트 할 수 없습니다.

<input type="text" data-ng-model="aadhaar" dashsep="'-'"> 

.directive('dashsep', function($timeout) { 
    'use strict'; 
    return { 
    restrict: 'A', 
    scope: { 
     dashsep: '=', 
     ngModel: '=ngModel' 
    }, 
    require: '?ngModel', 
    link: function(scope, element, attr) { 
     element.bind("keyup", function (event) { 
      var formattedAdh = ""; 
      //console.log(element.val()); 

      var test = element.val().toString(); 

      for(var i=0;i<=test.length-1;i++){ 
       //console.log(test[i]); 
       if(i%4 === 0 && i>0){ 
        formattedAdh+= scope.dashsep; 
       } 
       formattedAdh += test[i]; 
      } 

      // Following script is not updateing the ngModel/textbox with the formatted value properly // 
      /* 
       //element.val(scope.$eval(formattedAdh)); 
       // OR 
       //scope.ngModel = formattedAdh; 
      */ 

      // Following output is showing proper value IF ABOVE SCRIPT IS COMMENTED // 
      console.clear(); 
      console.log(formattedAdh); 
     }); 
    } 
    }; 
}); 

전체 스크립트가 Plunker에 제공됩니다.

답변

0

샘플 코드에 대한 이해에서 매 4 자마다 대시를 추가하려고합니다. 즉, 사용자가 "aaaabbbbcccc"를 입력하면 input[text]에 "aaaa-bbbb-cccc"가 표시되고 이에 따라 범위 모델이 업데이트됩니다.

이 가정하에 범위 모델 표현식을 직접 업데이트하는 대신 형식화 된보기 값으로 $setViewValue을 호출해야합니다. $setViewValue은 범위 모델 표현식을 업데이트하기 전에 ngModelController의 내부보기 값 및 내부 모델 값으로 새보기 값을 동기화하기 때문에 중요합니다.

새 범위 모델이 성공적으로 변경되었다고 가정합니다. 즉, 파서와 유효성 검사기를 전달하면 $viewChangeListeners이 실행됩니다. 여기에서 $render으로 전화하여 새보기 값으로 DOM을 업데이트 할 수 있습니다.

변경 사항은 plunker입니다. 당신이 ngModelController의보다 자세한 설명을 얻을 찾고 있다면

link: function(scope, element, attr, ngModelController) { 
    element.on('keyup', function (event) { 
     var viewValue = element.val().toString(); 

     // add a dash every 4 characters 
     if ((viewValue.length + 1) % 5 === 0) { 
     viewValue += scope.dashsep; 
     } 

     // angular updates the internal view value, internal model, then scope model based on DOM 
     ngModelController.$setViewValue(viewValue, event); 
    }); 


    ngModelController.$viewChangeListeners.push(function(){ 
     console.log(ngModelController.$modelValue); 
     // when model changes, call $render to display the latest view value 
     ngModelController.$render(); 
    }); 
}) 

,이 기사는 도움이 될 수 https://medium.com/product-at-catalant-technologies/i-have-to-relearn-angulars-form-api-every-time-i-use-it-83287c521968#.f5hle083e