Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

Is it possible to transform a value between view and model in AngularJS for input?

New to AngularJS. Trying to figure out how I would accomplish this, or if it is possible at all.

I know I can bound a value to the input box by using

<input type="number" ng-model="myvalue">

But what if I want it such that the value between the model and the view is transformed?

For example, for currency, I like to store my value in cents. However, I want to allow my users to enter dollar amounts. So I need to convert the value by a factor of 100 between the view and controller, i.e. in the model I would have 100, and in the view, I would have 1.

Is that possible? If so, how can I achieve that?

question from:https://stackoverflow.com/questions/13420693/is-it-possible-to-transform-a-value-between-view-and-model-in-angularjs-for-inpu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I ran into the same problem as you. I started using wciu's solution but ran into an issue where the values would flicker between the cents and dollars. I ended up hooking into the pipeline that is used to do the binding between view and model.

merchantApp.directive('transformTest', function() {
  return { restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {

      if(ngModel) { // Don't do anything unless we have a model

        ngModel.$parsers.push(function (value) {
          return value*100;
        });

        ngModel.$formatters.push(function (value) {
          return value/100;
        });

      }
    }
  };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...