Displaying unique input values with ng-model

Within the controller, there is a variable that monitors the page index (starting at 0) for a paginated table:

var page {
  pageNumber: 0;
}

Query: How can I display this pageNumber variable in the HTML, but always incremented by +1? (since the index=0 page represents the first page and should be displayed as Page 1)

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

In addition, when the model is updated, the value in the input field should automatically adjust accordingly (incremented by +1).

Answer №1

Utilizing $formatters and $parsers seems like the appropriate approach in this scenario. By manipulating the model's property directly, there is no need to add an extra dummy property. You can refer to the documentation here. Feel free to correct me if this isn't the intended use of $formatters and $parsers.

Take a look at the example below.

HTML code

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

JavaScript

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

Answer №2

To update your controller, modify the page object like this:

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

Next, adjust your element to the following:

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

This will display the incremented page number while maintaining the correct value of the actual page.pageNumber variable.

The use of getterSetter: true in the ng-model-options binds the model to a getter/setter function, enabling you to input values and retrieve them from that function. For more details, refer to the documentation for ngModel.

Answer №3

Here is a simple way to achieve this.

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

   };

Your HTML code should look like this:

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

For more details, please see this example on Plunker.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to modify the model of the directive

I'm facing an issue where additional elements added to my array within a controller of a directive are not being displayed in the view. What's even more frustrating is that when I print my model, it doesn't reflect the new elements that have ...

Tips on selecting specific data from a nested JSON array based on conditions and fetching just one value from the initial filtered result with Javascript (designed for Google Sheets)

Utilizing the TMDB API for retrieving movie data and integrating it into a Google Sheet. The original Google Sheet was revamped from Reddit user 6745408's "MediaSheet 3.0". This sheet incorporates a Javascript-based script. By following the patterns/c ...

Issue with implementing setTimeout on await fetch() result

I'm trying to figure out how to add a setTimeout to my request response when using await fetch. Currently, each response is being sent to a DIV in the HTML, but I want to introduce a delay of 5 seconds before each response appears. I attempted this s ...

having trouble loading marker in react leaflet within next.js

I am facing difficulty in implementing react leaflet Marker in my next.js project. Below is the code snippet where I have included my map component: const MapSearch = dynamic(import('../../components/Map'), { ssr: false, loading: () => ( ...

Easiest method for implementing event emitter in ES6

Here is the current setup for my event emitter: class Table { set onDiscard(cb) { this._onDiscard = cb; } notifyDiscard(s) { if (this._onDiscard) { this._onDiscard(s); } } } Dealing with multiple events using this method can b ...

Tick the checkboxes if they are found in the JSON data

After parsing this JSON object: [{"id_distrib":"1"},{"id_distrib":"44"},{"id_distrib":"4"}] I need to select the following checkboxes: <input id="1" class="cb_distrib_linux" type="checkbox"value="1">Achlinux <input id="2" class="cb_distrib_lin ...

Steps to display a NotFound page when the entered path does not match the route in module federation React micro frontends

Typically, if the provided path does not match, we display the NotFound page to the user using the following code snippet <Route path={"*"} component={NotFound} /> However, upon adding this code, I always get redirected to the home page ( ...

Discovering ways to determine if multiple strings are present within a single string using JavaScript

After writing this function, I noticed it only worked with a single string value. contains(input, words) { let input1 = input.split(' '); for (var i = 0; i < input1.length; i++) { if (input1[i] === words) { ...

Encountering the error code [$injector:unpr] regarding an unknown provider: $uibModalInstanceProvider

In my web application, I have a controller called AddPrice. This controller is invoked from a Price listing screen as a popup using the $uibModal.open method, where the controller is passed in as an argument. However, the controller is not defined within t ...

Using Vue-router and Typescript with beforeEnter guard - utilizing validated data techniques

As I utilize Vue along with vue-router and typescript, a common scenario arises where a single page is dedicated to displaying a Photo component. A route includes a beforeEnter guard that checks my store to verify the existence of the requested photo. ...

Avoid altering the state directly; utilize setState() to update it instead. Remember to follow react/no-direct-mutation

Here's the code snippet I'm working with: constructor(props) { super(props) this.state = { loginButton: '', benchmarkList: '' } if (props.username == null) { this.state.loginButton = &l ...

Creating Production Files for Web using RxJs and TypeScript

I am interested in developing a JavaScript Library using RxJs (5.0.0-Beta.6) and TypeScript (1.8.10). My TypeScript file is successfully compiling. Below are the files I have: MyLib.ts: /// <reference path="../../typings/globals/es6-shim/index.d.ts" ...

How to achieve the functionality of multiple inheritance using Object.create()

Seeking insights on implementing multiple inheritance in JavaScript. Various methods exist, each with pros and cons. However, there lacks a comprehensive analysis of Object.create() presented in an understandable manner. After conducting experiments, I hav ...

What is the best way to practice solving linked list problems from LeetCode on your personal computer?

Is there a way to execute the linked list programs on my local machine? I am able to run this code in their input field, but I'm having trouble running it on my local machine. function ListNode(val, next) { this.val = (val===undefined ? 0 : va ...

setTimeout executes twice, even if it is cleared beforehand

I have a collection of images stored in the img/ directory named 1-13.jpg. My goal is to iterate through these images using a loop. The #next_container element is designed to pause the loop if it has already started, change the src attribute to the next im ...

ReactJS: streamlining collection method calls using re-base helper functions

I have been struggling to find a way to integrate ReactJS with firebase. Fortunately, I came across the amazing re-base repository which perfectly fits my needs. fb-config.js var Rebase = require('re-base'); var base = Rebase.createClass({ ...

Creating an array dynamically by parsing a JSON object in Javascript

I am currently working with a JSON object that looks like this: var testJSON = [ { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_c", "AssetB": "asset_d" }, { "AssetA": "asset_c", " ...

What is the best way to adjust the height of a container to equal the viewport height minus a 300px height slider?

Forgive me for the rookie question, I know what I want to achieve should be simple but I seem to be having trouble articulating it in my search for solutions. Essentially, I am trying to set a section in HTML to the height of the viewport minus the height ...

Tips for including a variable in the src attribute

I am facing an issue with the img tag <img src='http://...../{{element}}'/> and encountering this error message: /%7B%7element%7D%7D 404 (Not Found) Can anyone guide me on how to add a variable to the src attribute in angular.js? ...

To set up MongoDB on your system, execute the following command: `npm install --

I've encountered a problem while attempting to install MongoDB on my personal computer for a Node project. I used the command line and ran npm install --save mongodb. Even though MongoDB appears in the dependencies section of my package.json file with ...