Displaying currency format in an input field using AngularJS filter

I'm currently dealing with an input field that looks like this:

 <input type="text" class="form-control pull-right" ng-model="ceremony.CeremonyFee | number:2">

Although it is displaying correctly, I've noticed that it's disabled. The error message I'm getting is "[ngModel:nonassign] Expression 'ceremony.CeremonyFee | number:2' is non-assignable". While I understand why this error occurs, I'm unsure how to resolve it for an input field. Any help would be greatly appreciated. Thank you.

Answer №1

input with ng-model is typically used for entering data, while the number filter is commonly used for displaying data. Since filter values cannot be bound, they are not compatible in this context. It's important to determine the purpose of the input element.

If you want the user to input their own number that needs validation, consider using the pattern attribute:

<input type="text" ng-model="ceremony.CeremonyFee" pattern="[0-9]+(.[0-9]{,2})?">

If you want the input to display a calculated value without user input, avoid using ng-model and instead use value:

<input type="text" value="{{ceremony.CeremonyFee | number:2}}" readonly>

Answer №2

SOLUTION:

Having trouble understanding your requirements, but if you simply want users to input two digits only, consider using basic HTML attributes like `min`, `max`, and `step`.

Here is a JavaScript solution, although not recommended:

angular.module('test', []).controller('TestCtrl', function($scope) {
  var vm = $scope;
  var testValue = 0;
  Object.defineProperty(vm, 'testValue', {
    get: function() { return testValue; },
    set: function(val) {
      val = Number(val);
      
      if(angular.isNumber(val) && (val < 100 && val > 0)) {
        console.log(val);
        testValue = val;
      }
    } 
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
  <div ng-controller="TestCtrl">
    <input style="display:block; width: 100%; padding: 1em .5em;" type="number" ng-model="testValue" />
  </div>
</section>


The `ng-model` directive needs a viewmodel assignable (or bindable) property, so adding a pipe won't work here.

angular.module('test', [])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="test" ng-init="testValue = 0">
  <label ng-bind="testValue | currency"></label>
  <input style="display:block;" ng-model="testValue" type="number"/>
</div>

Answer №3

An error message indicates that there is a 'non-assignable' expression in the ng-model attribute.

To resolve this issue, ensure you are only using ceremony.CeremonyFee.

The use of "|" in ng-repeat specifies which expression should be used as a filter.

If you want to pre-populate the <input> with initial data in your controller or link function, assign it an initial value like so:

$scope.ceremony = {
    CeremonyFee: 'My first ceremony'
}

Whenever the data in your <input> element changes, the CeremonyFee will also be updated accordingly.

Answer №4

I came across and successfully implemented the solution provided on this website.

http://jsfiddle.net/k7Lq0rns/1/

    'use strict';
    angular.module('induction').$inject = ['$scope'];
    angular.module('induction').directive('format',['$filter', function ($filter) {
      return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue)
            });

            elem.bind('blur', function(event) {
                var plainNumber = elem.val().replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
            });
        }
  };
}]);

It was relatively simple to implement.

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

Can a table with a checkered pattern be created in Ember.js with just Handlebars and ember-composable-helpers?

I'm new to working with Ember.js and I am attempting to create a simple checkered table. In my project, I am utilizing Bootstrap 4, ember-composable-helpers, and Handlebars. Is there anyone who can guide me on achieving this goal WITHOUT the use of ja ...

Protractor - Utilizing randomized data to enhance test capabilities

Currently, I am running multiple test suites simultaneously and hard coding the data for testing. For instance: element(by.name('email')).sendKeys(xxxxxx) element(by.name('password')).sendKeys('password') The email field in ...

What is the best way to reveal the square's id value upon hovering over it exclusively?

In this assignment, I am refraining from using HTML and focusing on JavaScript to create functionality. Here's my progress so far: document.addEventListener("DOMContentLoaded", function () { let button = document.createElement('button' ...

Learn how to implement RSS into your Next.js MDX Blog by integrating the `rss` module for Node JS. Discover the process of converting MDX content to HTML effortlessly

Having trouble converting MDX to HTML at the moment. This task is for Tailwind Blog You can find the complete code on Github here → https://github.com/tailwindlabs/blog.tailwindcss.com Below is the relevant code snippet: scripts/build-rss.js import fs ...

Easily utilize functions among Angular controllers without the need for $scope or $watch

In order to share a location with multiple controllers, I have created a service as shown below: angular.module("StockSampleApp") .service("Location", function () { this.currentLocation; }) The main controller in my application is res ...

Comparing JSON and JavaScript object arrays: Exploring the differences in outcomes and strategies for achieving desired results

Although it's not valid JSON, I've found that by declaring this as a variable directly in my code, I can treat it like an object. <script> // this will result in object var mydata = { users: [{ person: { ...

Struggling with extracting an array of objects from a JSON file and accessing individual attributes within each object?

As a newcomer to Typescript, I am eager to work with JSON and access its objects and attributes. However, I am encountering difficulties in achieving this. I have attempted using functions like 'for of' and 'for in', but unfortunately, ...

Challenges in Implementing Shadows with Animations in ThreeJS MeshDepthMaterial

I'm facing an issue where casting shadows through transparent parts of my Mesh using the MeshDepthMaterial causes the shadows of animated objects to stop moving along with the animation. You can see an example of this problem here: https://jsfiddle.n ...

Securely encoding information with PHP and decrypting it using JavaScript

I'm currently working with 2 servers. My goal is to generate a pair of keys, store the private key in local storage, and send the public key to my PHP server. The main objective is to encrypt data using the public key in PHP and decrypt it using Jav ...

steps for repairing a scoreboard

Is there a way to make my scoreboard increase by +1 point instead of +10? In my JavaScript code, I used intervals as it was the only solution that worked: let scoreInterval = setInterval(updateScore); let score = 0; function updateScore() { var poin ...

JQuery's document.ready function triggers prematurely on dynamically loaded HTML content

When loading dynamic content, I use the following method: $('#my-div').load('my.html'); The code inside my.html looks like this: <html> <head> </head> <body> <script> $(fu ...

The direction to the Excel document for conversion into JSON

I have a project in progress where I'm currently working on converting an Excel sheet to JSON. Once the data is converted, it will be displayed using jQuery Datatables on the browser. My code is functioning as expected, but I am encountering an issue ...

Can buttons be inserted into an Input control?

I am currently working on developing a custom timepicker that is compatible with both Internet Explorer and Chrome. The desired time format is 'hh:mm'. This is what I have so far: <input ng-model="timeHours" type="number" class="hours" placeh ...

Activate automatic click or force trigger JavaScript function

In the MVC view I am working with, there is a form that allows for file submission. //Submit file <% using (Html.BeginForm("MethodName","ControllerName", FormMethod.Post, new { enctype = "multipart/form-data"})) { %> <input type=" ...

When loading a page in NodeJS and Express, there are no initial displays, but upon refreshing the page, all data is successfully retrieved

Struggling to solve this issue that has been lingering for a while. I'm currently working on a project where a remote JSON file is loaded into memory, parsed, and the results are displayed on the page (using pug). Everything seems to be working fine ...

Incorporate an AngularJS directive within an Angular 7 component

Is there a method to dynamically integrate an AngularJS directive within an Angular 7 component? The AngularJS is in a separate project module with its own folder structure, including directives. Can these AngularJS directives be brought into the Angular ...

The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users. Interestingly, the error messages seem to appear fine in the developer to ...

Navigating errors during the distribution of numerous messages with SendGrid and Node.js

I have developed a command line application that interacts with a DynamoDB table to extract email addresses for items that have not yet received an email. The process involves creating customized message objects, sending emails using SendGrid's sgMail ...

The initial loading of jQuery DataTables shows duplicate entries

Expanding on my query from the previous day: jQuery AJAX call function on timeout Following the guidance provided in the response from yesterday's post, the table successfully reloads without requiring a full page refresh every 30 seconds. However, ...

How to Populate Object Literal with Multiple Objects in AngularJS

When I click on "Evan", I receive the following response: {"id":1,"name":"Evan"} If I click on "Robert", I will get: {"id":2,"name":"Robert"} Is there a way to modify this code so that it follows the aforementioned steps and generates an object similar ...