How to show different value of input element with ng model?

In the controller, if there is a variable that tracks the index (starting at 0) of the page for the pagination table:

var page { pageNumber: 0; } 

Question: how can I show this pageNumber variable in html, but always increase by +1? (since page index = 0 is obviously the first page and should therefore be displayed as Page 1 )

 <input type="text" ng-model="page.pageNumber"> 

In addition, when the model is updated, the input value should automatically change (again: also increased by +1).

+8
javascript angularjs
source share
3 answers

I think this is a precedent for $ formatters and $ parsers. They act on the property of the model, and there is no need to create a dummy property on the model. The documentation is here . Please correct me if this is not used for $ formatters and $ parsers.

See below.

HTML markup

 <body ng-app="app" ng-controller="mainCtrl"> {{page}} <input paginated-index type="text" ng-model="page"> </body> 

Js

 var app = angular.module('app', []); app.controller('mainCtrl', function($scope) { $scope.page = 0; }); app.directive('paginatedIndex', 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; }) } } }); 
+7
source share

In your controller, change your page object to this:

 $scope.page = { displayedPage: function(num) { if(arguments.length) { $scope.page.pageNumber = num - 1; return num; } else { return $scope.page.pageNumber + 1; } }, pageNumber: 0 } 

And then you do the following:

 <input type="text" ng-model="page.displayedPage" ng-model-options="{ getterSetter: true}" /> 

This will display the page number plus 1, but leave the actual page.pageNumber variable the way it should be.

The getterSetter: true parameters that I added will bind the model to the getter / setter function, which allows you to pass an argument - in this case, the entered page number - and return from this function. You can read more about this in the documentation for ngModel

+7
source share

you can try using something like this.

  $scope.data=$scope.page.pageNumber+1; $scope.fuc=function(){ $scope.page.pageNumber=$scope.data-1; }; 

and your html will look like

  <input type="text" ng-model="data" ng-change="fuc()" > 

check out this plunker plunger

+2
source share

All Articles