2016-08-05 10 views
2

ユーザーがいくつかの番号を入力するフォームがあります。これらの数字はインデックスです。問題は、サーバーにモデルをポストしているときにインデックスをゼロベースにする必要があるということです。しかし、インデックスは、ユーザーのために1ベースとして提示する必要があります。ユーザーの1つの値を表示しますが、モデル内に別の値を表示します

インデックスがのモデルの場合はと表示されます。

これは可能ですか?私は実際に転記する前にそれを手動で変更するのではなく、実際には1つではなく複数の値であるためです。

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>

答えて

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>

+0

魅力的な作品です。 – smoksnes

+0

それを聞いてうれしいと私は助けることができる嬉しい:) – thepio

1

あなたは他の方法で考えなければなりません。

0ベースのインデックスを含み、ユーザに表示する場合、単純にこのコード

{{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> 
に1を追加する必要がありますあなたのモデル