简体   繁体   中英

Angular.js set input field value using ngModel

I'm trying to make an input that formats currency using angular.js, preferably when focus is lost. Here's what I have so far

<div layout-fill>
    <md-input-container layout-fill currency class="number-range">
        <input placeholder="From"
               type="text"
               name="from"
               precision="{{rangeController.precision}}"
               ng-blur="pls = {{pls | currency}}"
               ng-model="pls"/>
    </md-input-container>
</div>

where precision always evaluates to 2 . I know this is wrong (because it isn't working), but I can't find anything in the documentation about this, and everything I google talks about huge JQuery libraries that can format in any of a hundred different international currencies. I want to use neither JQuery, nor any external code and this seems pretty simple, so I can't figure out why no one has ever tried to do it.

I believe this plunker does what you're asking. It uses this directive:

   .directive('blurToCurrency', function($filter){
  return {
    scope: {
      amount  : '='
    },
    link: function(scope, el, attrs){
      el.val($filter('currency')(scope.amount));

      el.bind('focus', function(){
        el.val(scope.amount);
      });

      el.bind('input', function(){
        scope.amount = el.val();
        scope.$apply();
      });

      el.bind('blur', function(){
        el.val($filter('currency')(scope.amount));
      });
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM