The formatter/render function in Angular Directive fails to refresh

Recently, I created a straightforward directive that converts minutes into a range slider while also displaying hours and minutes alongside. However, I encountered an issue where although moving the range slider updates the scope triggering Watch and Parser functions, Formatters/Render functions do not get called again.

As a result, the minutes update and reflect changes in the model, but the directive's internal hours and minutes remain static and never update unless alterations are made from outside modifying the ng-model value.

This situation has left me puzzled as other similar directives function properly. Not sure what could be causing this anomaly.

// Below is a condensed version
angular.module('TestApp', ['TestDirectives']);

angular
.module('TestDirectives', [])
.directive("rangeMinutes", [function RangeMinutesDirective () {
    return {
        require: 'ngModel',
        replace: true,
        scope: true,
        templateUrl: 'minutesHoursRange.html',
        link: function (scope, element, attributes, ngModelCtrl) {

            ngModelCtrl.$formatters.push(function (modelValue) {
                var totalMinutes = (modelValue ? modelValue : 0);
                return {
                    totalMinutes : totalMinutes,
                    hours : Math.floor(totalMinutes/60),
                    minutes : parseInt(totalMinutes%60, 10)
                };
            });

            ngModelCtrl.$render = function () {
                if (!ngModelCtrl.$viewValue) {
                    ngModelCtrl.$viewValue = {
                        hours: 0, minutes: 0, totalMinutes: 0
                    };
                }
                scope.totalMinutes = ngModelCtrl.$viewValue.totalMinutes;
                scope.hours = Math.floor(scope.totalMinutes/60);
                scope.minutes = parseInt(scope.totalMinutes%60, 10);
            };

            scope.$watch('totalMinutes', function () {
                ngModelCtrl.$setViewValue({
                  totalMinutes: scope.totalMinutes,
                  hours: scope.hours,
                  minutes: scope.minutes
                });
            });

            ngModelCtrl.$parsers.push(function (viewValue) {
                return parseInt(viewValue.totalMinutes, 10);
            });
        }
    };
}])
.controller("TestController", ["$scope", function ($scope) {
  $scope.testObject = { testValue: 40 };
}]);

Directive's Template:

<div class="form-inline minutesHoursRange">
    <div class="form-group">
        <label>
            <input type="range" min="0" max="100" step="1" class="form-control"
               data-ng-model="totalMinutes"/> {{hours}} hrs {{minutes}} mns
        </label>
    </div>
</div>

View:

<body data-ng-app="TestApp" data-ng-controller="TestController">
    <div data-ng-model="testObject.testValue" data-range-minutes></div>
</body>

Answer №1

If the $watch function for the totalMinutes property is missing, you can simply add it like this:

scope.$watch('totalMinutes', function updateValue () {
        scope.hours = Math.floor(scope.totalMinutes/60),
        scope.minutes = parseInt(scope.totalMinutes%60, 10);
});

Once you do that, everything should work smoothly.

Check out this Working 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

Sending a batch of items through an ajax request

I am faced with a challenge where I have a collection of data stored within multiple objects. Within each object, there is an ID and a status, while the main object contains a type and form id. The issue arises when trying to post the result via ajax as ...

Having trouble toggling the navbar on and off in mobile. Error message: Unable to read parentnode of undefined

When I try to make my mobile navbar full screen on a mobile device, the hamburger button works as expected when clicked. Initially, all the links are displayed in full page view, but once I click on a link, it disappears and takes me to the respective sect ...

Transferring data between functions within the same controller in AngularJS

I have implemented two functions to handle the timing of a process, one for starting and one for stopping. Here is the code snippet: $scope.start = function(data) { $scope.time = { id: '', mainId: data.id, start: &ap ...

Utilizing Javascript to Open a New Tab from Drupal

I'm attempting to trigger the opening of a new tab when a specific menu link is clicked within a Drupal website. My initial approach was to incorporate JavaScript directly into the content of the page, but unfortunately this method has not been succes ...

Most efficient method for dynamically changing HTML content with JavaScript

Can anyone provide guidance on how to switch HTML content using JavaScript? For example: if($sid == 0) {insert one HTML code} else {insert another HTML code} Which method is preferable - LESS, jQuery, CSS3, etc? ...

Issue: Angular JS radio input not functioning as expected

Below is the code snippet in question: <div ng-controller="TestController"> <input ng-repeat="item in array" ng-model="selected.name" value="{{item.name}}" type="radio"></input> </div> <script type="text/javascript"> ...

Unable to access information through ajax when connecting to mysql database

Having a code that can add, edit, delete and view is good. When all the codes are put together in one file, it works fine. However, wanting to have it separately poses a problem with the "View" part. Despite trying to search for a solution, the functionali ...

Ways to extract variables from a component and utilize them in App.js

Despite my efforts to search online, I could not find the answer or understand what I needed to. My issue: I need the "inputVal" variable from the "InputField.js" component to be accessible in the "App.js" component (specifically in the fetch request where ...

Steps to retrieve an ext.js grid using data from a database

I've been struggling to make a basic Ext.js application work, which is supposed to pull data from a database and show it in an Ext.js grid. However, all I keep getting is "Failure:true". If you could help me identify the mistake, that would be great. ...

The success callback method is no longer correctly referencing the variable due to a change in the AJAX request

Imagine you have a table in your HTML file with the following rows, where {{ }} represent variables: <tr id="{{ object.id }}"> <td class="name">{{ object.name }}</td> </tr> <tr id="{{ object.id }}"> <td class="nam ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

setTimeout is only effective for durations less than 1000 milliseconds

I am trying to implement a timeout function that displays an alert two seconds after a form is submitted. The code I have tried using does not seem to be working as expected: $(document).ready(function() { $("#newsletter").submit(function() { setTi ...

Error encountered while executing node server.js for Azure IoT Hub due to incorrect flags provided in the RegExp constructor

Currently, I am attempting to execute 'node server.js' in order to establish a connection between my Raspberry Pi device and Azure through the Azure IoT Hub. However, upon running the command 'node server.js', an error message is displa ...

Is it possible to use jquery to specifically target classes?

I am trying to achieve the following: $('.class.img').css('cellpadding', variable); However, this code does not seem to be working as expected. Despite searching online, I have not been able to find a solution. Any assistance on how to ...

My objective is to show the div element just once using AngularJS

Here's the scenario I want to show this div just once, not multiple times: //angular js code $scope.arr=["sunday","mpnday","tuesday"]; //html view <ul> <li ng-repeat="x in arr"> <div><p>{{ x }}</p> </div> & ...

`<div>` element with a class of "button" that listens for

I've been attempting to use a userscript to automate a button click. Inspecting the element reveals the button code as: <div class="q-w-btn cl"></div> Unfortunately, the button lacks an id attribute, making it difficult for me to select ...

What is the best way to identify a particular subtype of HTMLElement based on its tag name and then save that element within another one?

I have a function that generates a node and returns it. Here is an example implementation: addElement: function ({ parentNode, elementName, tagName, }) { // Creates and appends the new node. parentNode[elementName] = document.createEl ...

I encountered an issue trying to animate an OBJ file in Three.JS, even after successfully loading it into the browser

I have encountered a challenge with scaling and animating an object loaded into my web browser using WebGL. The issue arises when attempting to include animation code within the render( ) loop function, specifically with the 'object' variable whi ...

Managing file responses in Node.js

Hey there! I've been working on implementing ajax image upload and here's how far I've gotten. This is my index.html: <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8> <title>File Upload ...

React is choosing to re-render only one of the setState functions, neglecting the other

I'm currently in the process of developing a basic Tic Tac Toe game using React. The Objective: Each button in the game has its own state. When a button is clicked, it should change from ' ' to an 'X' and update the player's ...