ng-model 在输入和显示时操纵值

ng-model manipulating value when typing and displaying

我有以下变量:

$scope.pixelWidth = "30px";

我有一个这样的输入框:

<input ng-model="pixelWidth" />

我希望输入框内只有数字,但在键入时仍将 px 插入 $scope.pixelWidth

有没有办法做到这一点?

你可以通过手表功能来做到这一点。

$scope.$watch("pixelWidth",function(VariableValue){

// remove "px" from your variable and assign it again

$scope.pixelWidth=newValue;
});

是的,您需要创建一个指令并将格式化程序和解析器添加到 ngModelController. See working version on plunker

指令:

app.directive('modelSuffix', [function() {
  return {
    restrict: 'AE',
    require: '^ngModel',
    link: function(scope, element, attributes, ngModelController) {
          var suffix = attributes.modelSuffix;
          // Pipeline of functions called to read value from DOM 
          ngModelController.$parsers.push(function(value) {
            return value + suffix;
          });

          // Pipeline of functions called to display on DOM
          ngModelController.$formatters.push(function(value) {
            return value.replace(suffix, '');
          });
        }
  }
}]);

然后像这样使用它:

<input ng-model="pixelWidth" model-suffix="px"/>

我看不出有什么方法可以在不在控制器中使用第二个变量的情况下完成此操作。如果您将 $scope.pixelWidth 更改为包含 'px',它将最终出现在您的输入框中。这就是双向数据绑定的神奇之处,除了在这个用例中,结果对您来说可能不那么神奇。

您可能需要对输入框上的 ng-change 事件做出反应,以更改第二个影子变量。

<input ng-model='pixelWidth' ng-change='addPx(pixelWidth)'>

在控制器 JS 中

$scope.addPx = function(pw){
  $scope.withPx = pw + 'px';
}
<input type="text" name="userName" ng-model="pixel.value" ng-model-options="{ getterSetter: true }" />


var _myPixel = '0';
$scope.pixel = {
    value: function(pixel) {`enter code here`
     // Note that pixelcan be undefined for two reasons:
     // 1. Because it is called as a getter and thus called with no arguments
     // 2. Because the property should actually be set to undefined. This happens e.g. if the
     //    input is invalid
     return arguments.length ? (_myPixel = pixel.split("px")[0]) : _myPixel + "px";
  }
};

我要删除 setter 中的 "px" 并在 getter 中添加 "px"。

我希望这对你有用!