2014-07-24 2 views
0
나는이 입력 필드에 지시의 몇 가지를 사용하고

허용하지 :입력 0으로 디폴트됩니다 - 빈 값

<input valid-number type="tel" ng-model="planBody.campaign.campaignparams.budget" currency-input=""/> 

다음 지시어는 것 모두에 ""0 ""빈 재설정하거나 수 모델 업데이트 유형 (사용자 키 누르기와 vis를 통한) JavaScript :

.directive('currencyInput', function($filter, $browser) { 
    return { 
     require: 'ngModel', 
     link: function($scope, $element, $attrs, ngModelCtrl) { 
      var listener = function() { 
       var value = $element.val().replace(/,/g, ''); 
       $element.val($filter('number')(value, false)); 
      }; 

      // This runs when we update the text field 
      ngModelCtrl.$parsers.push(function(viewValue) { 
       return viewValue.replace(/,/g, ''); 
      }); 

      // This runs when the model gets updated on the scope directly and keeps our view in sync 
      ngModelCtrl.$render = function() { 
       $element.val($filter('number')(ngModelCtrl.$viewValue, false)); 
      }; 

      $element.bind('change', listener); 
      $element.bind('keydown', function(event) { 
       var key = event.keyCode; 
       // If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing. 
       // This lets us support copy and paste too 
       if (key == 91 || (15 < key && key < 19) || (37 <= key && key <= 40)){ 
        return; 
       } 
       $browser.defer(listener); // Have to do this or changes don't get picked up properly 
      }); 

      $element.bind('paste cut', function() { 
       $browser.defer(listener); 
      }); 
     } 

    }; 
}) 

.directive('validNumber', function() { 
    return { 
    require: '?ngModel', 
    link: function(scope, element, attrs, ngModelCtrl) { 
     if(!ngModelCtrl) { 
     return; 
     } 

     ngModelCtrl.$parsers.push(function(val) { 
     var clean = val.replace(/[^0-9]+/g, ''); 
     if (val !== clean) { 
      ngModelCtrl.$setViewValue(clean); 
      ngModelCtrl.$render(); 
     } 
     return clean; 
     }); 

     element.bind('keypress', function(event) { 
     if(event.keyCode === 32) { 
      event.preventDefault(); 
     } 
     }); 
    } 
    }; 
}) 

입력 필드에 빈 값을 허용하고 싶습니다. 지침 중 어느 부분을 변경해야합니까?

+0

나는 촬영을거야하고'$의 element.val ($ 필터 (라고 말할 'number') (value, false))'? – Kousha

+0

그게 뭐라고 생각하니? – nikjohn

+0

내 대답보기 – Kousha

답변

1

문제는 맨 위입니다. 여기에 $element.val($filter('number')(value, false))이 있습니다.

value을 필터링하고 $element으로 설정하고 있습니다. 빈 문자열을 필터링하여 숫자로 변환하면 0이됩니다. 당신이 원하지 않는 경우

, 나는 당신이 필터링하기 전에 테스트를 제안 :

// Check to see if value is null or empty. 
// If it is, then just assign the value to be an empty string. 
// Otherwise, filter the number. 
// Here I am using UnderscoreJS for the null/empty check, but you can use pure javascript. 
value = (_.isNull(value) || _.isEmpty(value)) ? '' : $filter('number')(value); 

// Now assign the new value 
$element.val(value);