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>