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">
You can write a filter to achieve the functionality
app.filter('addPercentSymbol', function () {
return function (item) {
return item + '%';
};
});
<input type="text" name="config_percentage" ng-model="percentage | addPercentSymbol">
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 }" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.