The ng-model in AngularJS is experiencing issues with two-way binding within a directive

Seeking to develop a straightforward Angular directive for handling currency input. The objective is to have it operate as a float in the model while showing two decimal places to the user.

The code implemented for this purpose is as follows:

//  Currency Input (Element Directive)
//  Basic text box ensuring 2 decimal place numeric input
//  Usage:
//      <currency
//          ng-model: string, angular model binding, optional
//      ></currency>
directives.directive('currency', function() {
    return {
        require: 'ngModel',
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<span class="currency"><input type="text" ng-model="text" ng-transclude /></span>',
        scope: {
            ngModel: '=amount'
        },
        link: function($scope) {
            return function($scope, elem, attrs, ctrl) {
                $scope.$watch("text", function(newVal) {
                    $scope.amount = parseFloat(newVal);
                    console.log();
                    console.log("text changed, recalculating amount");
                    console.log("Successfully converted", newVal, "into", $scope.amount);
                });
                $scope.$watch("amount", function(newVal) {
                    $scope.text = newVal.toFixed(2);
                    console.log();
                    console.log("amount changed, recalculating text");
                    console.log("Successfully converted", newVal, "into", $scope.text);
                });
            }
        },

        controller: function ($scope) {
            $scope.text = "test";
            $scope.amount = 0;

            grabScope = function() { //Debug function to allow global access to this scope
                return $scope;
            }
        }
    };
});

When implementing this directive, a textbox is generated with the text "test". However, editing within the textbox fails to update $scope.text and subsequently does not trigger the watches or update the model.

I've been pondering over this issue for some time now, but I suspect there might be a simple mistake on my part. Any insights?

Thank you,

YM

Answer №1

It seems like there might be an issue with the way your link property is set up.

Consider the following structure:


link: function($scope, elem, attrs, ctrl) {
    $scope.$watch("text", function(newVal) {
        $scope.amount = parseFloat(newVal);
        console.log();
        console.log("Text has changed, recalculating amount");
        console.log("Successfully converted", newVal, "to", $scope.amount);
    });
    $scope.$watch("amount", function(newVal) {
        $scope.text = newVal.toFixed(2);
        console.log();
        console.log("Amount has changed, recalculating text");
        console.log("Successfully converted", newVal, "to", $scope.store.text);
    });
}

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

Exploring the Versatility of Axios

Today, I implemented an AJAX request using Axios in JavaScript to submit form data. While the requests are being sent successfully, it seems that the backend is not able to receive the username and password information from the frontend. What could be ca ...

The jquery fancybox ajax modal popup fails to display in Internet Explorer 7

Recently, I utilized JQuery fancy box for the first time to display a menu list. When clicking on a specific item, the page is rendered properly in an iframe. However, if there is already an AJAX model popup present on the rendered page, it doesn't di ...

Tips on causing a forEach loop to pause for a regex substitution to occur

I have a project in progress for an email web app where I am working on replacing certain keywords (first name, last name, email) with the actual properties of the user. As of now, I am going through a list of recipients and modifying the email content to ...

What is the functionality of this JQuery Popup?

I'm facing an issue with my JQuery Popup. When the "Login" button is clicked, it hides the Login popup but doesn't show the Sign Up popup. How can I make sure that clicking on "Login" hides the Login popup and shows the Sign Up popup accordingly? ...

Ensure that the GraphQL field "x" with type "[User]" includes a selection of subfields. Perhaps you intended to specify "x{ ... }" instead

I am encountering an issue while attempting to execute the following simple query: {duel{id, players}} Instead, I received the following error message: Field "players" of type "[User]" must have a selection of subfields. Did you mean & ...

Looking to customize scrolling behavior when navigating back in Next.js?

I have a function in my index.js file that fetches a list of posts like this: const Index = (props) => { return ( <div> {props.posts.map((each) => { return ( <Link scroll={false} as ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...

Assigning active classes based on the href attributes of child <a> tags

I've created a navigation structure as follows: <ul class="page-sidebar-menu"> <li class="menu"> <a href=""> <span class="title">Menu Item</span> <span class="arrow"></span> < ...

Minimizing the frequency of getElementById calls for the same HTML element

When dealing with repetitive function calls using the same element as a parameter, is it more effective to store the element as a global variable? For instance, imagine a function that is triggered on every key press and takes an element as an argument. ...

`Only firing event listener once`

I have created a JS module where I am adding a click event to all links that match a specific selector. Here is an example of how it's done: var Lightbox = (function () { var showLightbox = function () { // this does stuff }; var init = fu ...

Can you explain why there is a discrepancy in the canvas coloration?

When I try to draw a line on my canvas with color "#ca5100", the actual color that appears is "#e4a77f". Why does this difference occur and how can I ensure that the correct color is set? var ctx = document.getElementById("mycanva").getContext("2d"); ct ...

Why do I receive the error message "Error: Objects are not valid as a React child (found: [object Promise])" in NextJS13?

I'm feeling overwhelmed by this issue and unsure of how to resolve it. Here is the code that is causing trouble: 'use client' import React, { useState } from 'react' import AnimatedDiv from '../../../(shop)/(components)/animat ...

The best approach for setting a select value and managing state in React using TypeScript

Currently, I am in the process of familiarizing myself with TypeScript within my React projects. I have defined a type for the expected data structure (consisting of name and url). type PokedexType = { name: string; url: string; } The API respon ...

Submitting Forms in Django with AJAX for Seamless User Experience

As a newcomer to Python, I might be missing an easy fix. I'm attempting to create a registration form using Jquery with Django. I've been following this tutorial When I click the button, I see a success message in the alert, but nothing gets sa ...

Are there alternative approaches to launching processes aside from the functions found in child_process?

Having trouble with NodeJS child_process in my specific use case. Are there other methods available to start processes from a node.js application? So far, Google has only been pointing me towards child_process for all of my inquiries. Edit I am looking to ...

How can we enable a sitemap for web crawlers in a nodejs/express application?

Looking to enable sitemap for web crawlers in nodejs/express? I am trying to figure out where I should place my sitemap folder/files within the application flow and how to allow access for web crawlers. Currently, when visiting domain/sitemap/sitemap.xml, ...

Receiving "this" as an undefined value within the TypeScript class

Currently developing a rest api using express.js, typescript, and typeorm. Initially thought the issue was with AppDataSource, but it seems to be functioning properly. Below is my controller class: import { RequestWithBody } from '@utils/types/reque ...

Sending an array from native IOS to JavaScript involves using a bridge or communication channel to

Currently developing an application that involves sending data from JavaScript to a native iOS controller. Wondering what is the best method for sending an array from the iOS controller to a JavaScript file. Appreciate any guidance, thank you. ...

Ways to verify the nodemon version that is currently installed on your local machine

On my Windows 10 machine, I recently installed nodemon locally in a project and now I'm curious to know which version is installed. Can someone please share the command to check the version of nodemon without needing to install it globally? My aim is ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...