我有一个用户输入一些数字的表格。这些数字是索引。问题是,当我将模型发布到服务器时,我需要将索引从零开始。但应该为用户提供索引作为一个基础。
因此,当模型的索引 4 时,应将其显示为 5 。
有可能这样做吗?我不想在发布之前手动更改它,因为它实际上是几个值,而不仅仅是一个。
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.model = {
index: 3
}
// Later I post the model with ajax.
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Enter index: <input type="number" ng-model="model.index"><br/><br/>
Actual index is <strong>{{model.index}}</strong> (Should be one less than what is shown in input)
</div>
</div>
&#13;
答案 0 :(得分:5)
你可以制定一个指令来改变显示给用户的值,如下所示:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.model = {
index: 3
}
// Later I post the model with ajax.
}
myApp.directive('correctIndex', function()
{
return{
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelController)
{
ngModelController.$formatters.push(function(value)
{
return value+1;
})
ngModelController.$parsers.push(function(value)
{
return value-1;
})
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Enter index: <input correct-index type="number" ng-model="model.index"><br/><br/>
Actual index is <strong>{{model.index}}</strong> (Should be one less than what is shown in input)
</div>
</div>
答案 1 :(得分:1)
你应该以另一种方式思考。
您的模型应包含基于0的索引,并在向用户显示时,只需使用此代码添加1
{{model.index + 1}}
<强>控制器强>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.model = {
index: 0
}
// Later I post the model with ajax.
}
<强> HTML 强>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Enter index: <input type="number" ng-model="model.index"><br/><br/>
Actual index is <strong>{{model.index + 1}}</strong>
</div>
</div>