简体   繁体   English

Angular.js使用ngModel设置输入字段值

[英]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. 我正在尝试使用angular.js进行格式化货币的输入,最好是在焦点丢失时。 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 . 精度始终评估为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. 我知道这是错误的(因为它不起作用),但我在文档中找不到任何关于此的内容,而且我在google上讨论了可以使用百种不同国际货币格式化的大型JQuery库。 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. 我想既不使用JQuery,也不使用任何外部代码,这似乎很简单,所以我无法弄清楚为什么没有人试过这样做。

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));
      });
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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