我想在不影响底层模型变量的情况下更改 angularjs 中 ng-model 的 View 值。我在 Controller 中定义了一个范围变量 markPercent。
$scope.markPercent = 0.43;
我正在尝试使用 ng-model 从我的 View 中访问它。
<input type="text" ng-model="markPercent">
此输入在 View html 中显示 0.43。我想要的是 View html 中的 43,而不影响 $scope.markPercent 的值。此外,如果用户更改输入字段中的值,则应以相同方式修改范围变量(例如:如果用户输入 65,则 $scope.markPercent 应为 0.65)。事实上,我不想每次都在 watch 内将它乘以和除以 100(我现在就是这样做的)。我们如何以 Angular 方式进行?
最佳答案
ngModel.$parsers
/ngModel.$formatters
管道 ( ref ) 就是这种情况。您将需要一个要求
ngModel
并将其自己的代码放入这两个管道的指令。例如:
app.directive("percent", function() {
/** Convert a string view value to percent float from 0.0 to 1.0. */
function parser(value) {
// implement this
}
/** Convert a float from 0.0 to 1.0 to percent. */
function formatter(value) {
// implement this
}
return {
restrict: "A",
require: "ngModel",
link: function(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(parser);
ngModel.$formatters.push(formatter);
}
};
});
简单解析器/格式化器的工作示例:http://jsfiddle.net/748j30ha/
关于javascript - 如何在不影响 AngularJS 中的原始变量的情况下操作 View 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26484832/