Angular JS: Keeping a directive in sync with changing values

There is a directive in my code that splits decimals from a number and displays it with different styles on the view. However, I am facing an issue where the values do not update when the input changes.

I frequently utilize this directive to showcase currency related information in the view.

Here's how the directive looks:

app.directive('money', function(){
    return {
        restrict: 'E',
        scope: {
            money: '@'
        },
        controller: controller,
        controllerAs: 'dvm',
        bindToController: true,
        template: '<h2><sup>$</sup>{{ dvm.dollar }}<sub>.{{ dvm.cents }}</sub></h2>'
    };

    function controller(){
        var parts = parseFloat(this.money).toFixed(2).split(/\./);
        this.dollar = parts[0];
        this.cents = parts[1];
    }
});

I need to update these values multiple times based on user selections, but currently, they do not reflect the changes made by the user. What could be the best solution to address this issue?

Answer №1

To ensure your model stays updated, it's important to include a link function that monitors changes and applies them accordingly:

Visit this link for a live example

HTML

<div ng-app="myModule" ng-controller="cont">
  <input ng-model="myMoney" type="number">
  <money ng-model="myMoney"></money>
</div>

JavaScript

var app = angular.module('myModule', [])
app.controller('cont', function($scope) {
  $scope.myMoney = 0;
})
app.directive('money', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '=' //bi-directional binding
    },
    template: '<h2><sup>$</sup>{{dollars}}<sub>.{{cents}}</sub></h2>',
    link: function(scope) {
      scope.dollars = 0;
      scope.cents = 0;
      scope.$watch('ngModel', function(newval) {
        if (newval) {
          var parts = parseFloat(scope.ngModel).toFixed(2).split(/\./);
          scope.dollars = parts[0];
          scope.cents = parts[1];
        }
      });
    }
  }
});

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

The call stack size has been exceeded in Next.js, resulting in a RangeError

Currently attempting to deploy my project on vercel.com but encountering an error specifically with 3 pages that have no internal errors. An error occurred while prerendering the page "/applications". For more information, visit: https://nextjs.org/docs/me ...

Display blanks rows after running a v-for loop

I am currently developing a vue component file where I have successfully fetched data using Laravel WebSockets. The issue I am encountering is that when I try to display the selected data in a table within the template tag, the rows in the table are bein ...

Utilize VueJS to remove a designated HTML div upon clicking the delete button

I'm having trouble with a delete button on my input fields. The goal is for the delete button to remove all related input fields when clicked, but it's not working as expected. HTML <div v-for="index in 10" class="form-group ro ...

AngularJS Get request returned HTTP Status 0 while trying to retrieve JSON data

I'm having an issue with my $http.get request in AngularJS. When I try to retrieve a JSON file from a certain URL, I keep getting a status of 0. Strangely enough, when I download the same JSON file and run the get request locally or use Python with th ...

Reveal the concealed button with a jQuery click event

I have a simple question that has been elusive to find an answer for on the internet. Can anyone please help? <input hidden="true" class="btnsubmit" id="myaddslide2" onClick="UPCURSLIDE()" type="button" value="UPDATE"> <script> function ...

Header buttons not displaying on FullCalendar

I have implemented fullCalendar in my project, but I am facing an issue with the header section. The title is displaying correctly, however, the next, prev, and month view buttons are missing. When I remove 'title' from the code, it does adjust ...

Ways to retrieve and contrast the border style of an image utilizing javascript

I'm currently attempting to identify images on my webpage that have the style border: 1px #c6c6c6 solid; let images = document.getElementsByTagName('img'); for (let i = 0; i < images.length; i++) { if (images[i].style.border === "1px ...

Save the ID of the list item by wrapping it and storing it in a table cell

I need help with a situation where I have a list of items stored in table cells, and each cell contains a list item. My goal is to save the id of each list item into the cell that contains it. For example: <td><li id='itemID'>content ...

The division element nested within a select tag

HTML: <div class="row"> <div class="form-group"> <div class="col-xs-10"> <label for="class_code_reservation">Class Code</label> <select type="text" class="form-control" id="class_code_reservation" na ...

Access the child scope's attribute within the parent scope in AngularJS

angular.module('myApp',[]) .controller('Parent',['$scope',function($scope){ //no specific definition }]).controller('Child',['$scope',function($scope){ $scope.user={name:''}; //create a us ...

Experiencing an Internal Server Error while attempting to upload a product using AngularJS in the MEAN Stack

I'm currently struggling with an Internal Server error while trying to add a product through the http service ($http.post) in AngularJS. To provide you with the necessary details for assistance, here are the key files involved: **index.js : This file ...

Stopping an endless loop in JavaScript by pressing a key on the keyboard can be a useful

I've been working on creating a JavaScript game and am currently tackling the challenge of implementing gravity. One crucial aspect I need to address is creating an infinite loop without causing the browser to crash. Is there a way for me to include a ...

Tips for optimizing an AJAX website for search engine crawling

If you're looking for an example of a crawlable AJAX website utilizing HTML5, CSS3, and history.pushState(), check out the following site: (for more information, visit ) However, keep in mind that this site assumes server-side ...

What steps can I take to prevent encountering a Typescript Error (TS2345) within the StatePropertyAccessor of the Microsoft Bot Framework while setting a property?

During the process of constructing a bot in Typescript, I encountered TS2345 error with Typescript version 3.7.2. This error is causing issues when attempting to create properties dynamically, even if they are undefined, or referencing them in the statePro ...

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

Angular, a Self-sufficient Module of Cascading Style Sheets

I have developed a factory that generates HTML content. I want to showcase this generated HTML within a specific section of my application, without its CSS affecting the rest of the site, and vice versa. While using an iframe is one option, I believe there ...

Establishing seamless transitions between various interfaces within my application

Hello everyone, I am developing an app in React Native and I have successfully implemented a login system. However, I am facing issues with routing between different screens. For example, I have distinct flows such as the signup flow: 1) User enters phone ...

Is there a way to determine the length of the visible section of an overflowing element?

Currently, there is a table with numerous rows causing it to overflow the vertical axis of the document viewport: https://i.sstatic.net/YoqKk.png As you can observe, only a portion of the table is visible when the document loads. How can we determine the ...

Numerous criteria for implementing ng-class

Can I use this code snippet? <button href="#" ng-class="{'disabled' : form.mail.$invalid && form.firstName.$invalid }"></button> I initially believed it was correct, but unfortunately, it doesn't seem to be functioning ...

The problem I am encountering with particles.js

Having an issue with the particles.js library where the particles are displaying beneath the elements despite setting the Z-index. I have tried various solutions from CSS, Stack Overflow, Google, and YouTube but none have been effective. Here is my code s ...