如何添加'%'char添加到具有ng模型属性的输入视图中

How to add a '%' char to the view of input with a ng-model attri?

本文关键字:添加 属性 ng 模型 视图 输入 char 何添加      更新时间:2023-09-26

var sliceApp = angular.module('sliceConfig', []);
sliceApp
    .filter('addPercentSymbol', function()
    {
        return function(value){
            return value + '%';
        };
    })
    .directive('valWithPercentile', function(val)
    {
        if(angular.isDefined(val))
            $scope.speed_print_percentage = val.substring(0, val.length - 1);
        return $scope.percentage + "%";
    })
    .controller('sliceConfigController', ['$scope', '$http', function($scope, $http)
    {
        $scope.speed_print_percentage = 40;
        $scope.speed_print = $scope.speed_print_percentage / 100 * 150;
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sliceConfig" ng-controller="sliceConfigController">
  <label>打印速度</label>
  <input placeholder="40%" type="text" name="speed_print_percentage" ng-model="speed_print_percentage | addPercentSymbol"/>
</div>

我的App.js中有一个$scope.percentage = 40。我想在输入中显示40%作为默认值。我知道如果我设置$scope.percentage = '40%',它会起作用。我想知道有没有一种方法可以只设置$scope.percentage = 40来避免服务器端进程。

<input type="text" name="config_percentage" ng-model="percentage">

您可以编写一个过滤器来实现功能

app.filter('addPercentSymbol', function () {
  return function (item) {
    return item + '%';
  };
});
<input type="text" name="config_percentage" ng-model="percentage | addPercentSymbol">

您可以创建一个指令。你可以搜索旧的SO问题(例如这个)。

如果重用性不是一个问题,那么简单的解决方案就是使用ngModelOptions,

在控制器中,

sliceApp.controller('sliceConfigController', ['$scope', '$http',     function($scope, $http)
{
    $scope.speed_print_percentage = 40;
    $scope.speed_print = $scope.speed_print_percentage / 100 * 150;
    $scope.valWithPercentile = function(val)){
        if(angular.isDefined(val){
            $scope.speed_print_percentage = val.substring(0, val.length - 1)
        }
        return $scope.speed_print_percentage + "%"
    }
}]);

在Html中,

 <input type="text" name="config_percentage" ng-model="valWithPercentile" ng-model-options="{ getterSetter: true }" />