Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  29] [ 2]  / answers: 1 / hits: 8086  / 8 Years ago, wed, february 10, 2016, 12:00:00

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



var page {
pageNumber: 0;
}


Question: how can I show this pageNumber variable in the html, but always incremented by +1? (as the index=0 page is obviously the 1st page and should thus be shown as Page 1)



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


Also, when the model gets updated, the value in the input should automatically change (again: also incremented by +1).


More From » angularjs

 Answers
5

I think this is a use-case for $formatters and $parsers. They operate on the model's property and there is no need to create a dummy property on the model. Documentation here. Please correct me if this is not the use case for $formatters and $parsers.



Please 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;
})
}
}
});

[#30906] Tuesday, February 9, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylor

Total Points: 334
Total Questions: 100
Total Answers: 111

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;