Display the input value in AngularJS in a customized format without changing the format in the model

When receiving an integer indicating a duration in minutes, I want to display it as hours or days if it exceeds a certain value. The ng-model should still keep the value in minutes so that any user changes are reflected accurately.

For example: Reading '480 minutes' should display as 8 (hours). Reading '1440 minutes' should show as 1 (day). If the user converts that to 0.5 (day), the ng-model value should be 720 minutes.

I prefer to have the numerical part in an input field with the measurement unit (minutes/hours/days) in a label beside it.

A 'duration' filter has been created for this purpose:

myApp.filter('duration', function() {
    //Converts minutes into hours
    return function(minutes) {
        var hours = Math.floor(minutes / 60);
        return hours;
    }
});

However, when applied to the following element:

...iterating through fields, where textField is the current iteration object
    <input type="number" class="text-input" ng-model="textField.CustomFieldValue | duration">

An error message appears in the console:

[ngModel:nonassign] Expression 'textField.CustomFieldValue | duration' is non-assignable. Element: <input type="number" class="text-input ng-pristine ng-untouched ng-valid" ng-model="textField.CustomFieldValue | duration">

Though my filter needs refinement, it does work as intended. The concern lies with the error message in the console.

Answer №1

It may not be advisable to attach the filter directly to the ng-model as it could lead to a potential max-digest error. My approach to this issue involves implementing ng-model formatters and parsers. For an in-depth guide on this topic, I recommend reading the following article:

Formatters and Parsers

In my solution, I have created new directives that handle the logic for hours and days. The formatters execute the logic, while the parser reverses it to prevent the ng-model from losing its original value. Take a look at the snippet below for a better understanding:

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope) {
  $scope.textField = 480;
});

app.directive('timeParser', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      timeParser: "@"
    },
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(minutes) {
        if (scope.timeParser === "hours") {
          return Math.floor(minutes / 60);
        } else if (scope.timeParser === "days") {
          return Math.floor(minutes / (60 * 24));
        } else {
          return minutes;
        }
      });

      ngModel.$parsers.push(function(minutes) {
        if (scope.timeParser === "hours") {
          return Math.floor(minutes * 60);
        } else if (scope.timeParser === "days") {
          return Math.floor(minutes * (60 * 24));
        } else {
          return minutes;
        }
      });

    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
  Minutes
  <input type="number" class="text-input" ng-model="textField">
  <br> Hours
  <input type="number" class="text-input" ng-model="textField" time-parser="hours">
  <br> Days
  <input type="number" class="text-input" ng-model="textField" time-parser="days">
</div>

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

Using HTML5 data attributes as alternative configuration options in a jQuery plugin can present challenges

I am currently in the process of creating my very first jQuery plugin, and I have encountered a challenge when attempting to extend the plugin to support HTML5 data attributes. The idea is for a user to be able to initialize and adjust settings simply by u ...

Leveraging Toaster Notifications in AngularJS for Custom Exception Management and Logging

Implemented the use of AngularJS Toaster for effective notification handling. To customize exception handling, set up in index.html as shown below <toaster-container toaster-options="{'time-out': 3000, 'position-class': 'toast ...

Attempting to transfer a newly created element from one location to another within the document after it has finished

I'm currently updating the design of my website. The currency selector app by Shopify is placed at the bottom, which has caused confusion for my international customers. To resolve this issue, I want to move it to a specific div class called .CSPositi ...

The Google Pie chart is displaying outside of the designated div area when placed inside a dropdown menu

Encountering an issue with my pie chart rendering outside of its parent div when placed within a dropdown menu. The chart successfully loads after the page is loaded, but only displays correctly if I hover over the dropdown and allow it to load. If I do ...

"Empty $stateParams Issue Encountered in Angular UI-Router While Using My Directive

I have developed a unique directive in my angular application for a custom navbar. The controller of this directive utilizes $stateParams to access a variable named lang, as shown below: .config(function($stateProvider, $urlRouterProvider, LANG) { $u ...

Steps for retrieving the currently selected text inside a scrolled DIV

An imperfect DIV with text that requires a scroll bar For example: <div id="text" style='overflow:scroll;width:200px;height:200px'> <div style='font-size:64px;'>BIG TEXT</div> Lorem Ipsum is simply dummy text of th ...

Shifting hues of colors on website based on geographical location

Working on a new project, I encountered an issue with two elements sharing the same class but displaying different color shades. Has anyone experienced this before and knows what could be causing it? UPDATE Here is an excerpt of the code: The Class: .su ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Drop down list not showing array values

I am attempting to populate a dropdown list with elements from an array using the Document Object Model (DOM) within a for loop. However, I keep encountering an error stating that the dropdown list is null. Here is the JavaScript code I am using: var st ...

What is causing the malfunction in communication between my React app and Express server via fetch requests?

I am currently facing an issue while trying to connect my react js frontend (hosted on localhost for testing purposes, and also on my S3 bucket) to my node.js/express server deployed on an AWS Elastic Beanstalk environment. To resolve a CORS error, I recen ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, I’m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

Is JavaScript still running despite not displaying insecure items due to IE 8 security warning?

After a user completes a transaction on my site, the confirmation page displays Google conversion tracking code in a small JavaScript snippet. This code is located on my Wordpay callback page, which pulls data from the regular site (HTTP) to the Worldpay s ...

What is the best way to incorporate data from my API into my component?

App.js import { Text, View, Button, FlatList } from 'react-native'; import { useEffect, useState } from 'react'; import * as React from 'react'; const API = 'https://randomuser.me/api/users/'; const User = (props) ...

AngularJS RESTful Routing Masterclass

I am in the process of organizing my application using the Restful/Ruby convention /<resource>/[method]/[id]. In the past, when working with a server-side MVC framework like CodeIgniter, I would dynamically route based on the URI: For example: www. ...

What is the best way to accomplish this in Next.js?

I am working on a NextJs application and I need to include a new route /cabinet with its own navigation. The challenge is that the application already has a navigation bar defined in _app.js. Is it possible to create a similar setup like _app.js for /cab ...

Using a .NET Web-API controller variable as a parameter in a JavaScript function

I am looking to send a "variable" from the controller to a JavaScript function. The code I have implemented is as below: <div ng-controller="faqController"> <div ng-repeat="c in categories"> <h2 onclick="toggle_visibility(&apos ...

Utilizing a default value for undefined object property in VueJS interpolation

Is there a way to handle undefined object property values in VueJS interpolation by setting a default value? I am working with a computed variable called data that is initially undefined until a selectedDataId is chosen from a selectbox. As a result, Vue t ...

Creating a real-time text field update feature for a form using Google Script

One of my clients is dealing with a large number of contacts and to streamline the process, I created a form with a scrolling list for contact selection. However, the list has become too long to navigate easily. Is there a solution that would allow the c ...

Interactive Sideways Navigation Bar

showcases a sleek horizontal scrolling menu on mobile devices. I aim to replicate this functionality for a website I'm redesigning that features extensive navigation elements. Key Features: Left and right scroll button options Centered list item op ...

How is it that this JavaScript task does not trigger an error: const a = (1, 2, 3, 4);

let x = (5, 6, 7, 8); console.log(x); let y = 5, 6, 7, 8; console.log(y); In the example above, x will be assigned a value of 8, while the second line will result in an error. What is the reason behind the success of the first assignment? How does it qua ...