Kris Roofe Kris Roofe - 9 days ago 5
AngularJS Question

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



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>





I have a
$scope.percentage = 40
in my App.js. I want to display a 40% in my input as a default value. I know if I set the
$scope.percentage = '40%'
, it works. I want to know is there a way that just set
$scope.percentage = 40
to avoid server side process.

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

aaa aaa
Answer

You can create a directive. You can search older SO questions for this (eg. this).

If reusability is not a concern, simple solution would be to use ngModelOptions,

In controller,

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 + "%"
    }

}]);

In Html,

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