【问题标题】:Separate values for the model and view in your input输入中模型和视图的单独值
【发布时间】:2014-11-18 04:06:52
【问题描述】:

我想要做的就是将我输入的数字自动格式化为 $,因为我在输入中输入它,但将实际模型保留为没有 $ 的数字。我尝试了不同的方式,但我现在所拥有的只是如果我在模型中已经有一些值(而不是 null),它将用 $ 显示。但是,如果它为 null 或者如果我删除输入中的所有内容并从头开始,则这些值不会被格式化为 $ 。我究竟做错了什么? 这是一个jsfiddle

http://jsfiddle.net/rmzqomzz/1/

angular.module('HelloApp', []);

function myTest() {

 return {
  restrict: 'EA',
  require: 'ngModel',
  link: function(scope, element, iAttrs, ngModel) {
      console.log(iAttrs.myTest);
      ngModel.$formatters.push(function(modelValue){
          if(!modelValue) return;
          if(iAttrs.myTest == 'money'){
              return '$ '+modelValue;
          }else{
              return modelValue +' %';
          }
      });
      ngModel.$parsers.push(function(viewValue){
          return viewValue.replace('$', '').trim();
      });
      scope.$watch(
          function(){
              return ngModel.$modelValue;
          }, function(newValue, oldValue){
              console.log('value changed '+ newValue);        
          }, true
      );


  }
 };
};

angular.module('HelloApp').directive('myTest', myTest);

angular.module('HelloApp').controller('HelloController', function($scope) {
$scope.mon = {'balu':null};
});

谢谢

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您是否尝试过使用过滤器?

    <input ng-model="num">
        <p>Value {{num | currency:"$"}}</p>
    </body>
    

    https://docs.angularjs.org/api/ng/filter/currency

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多