Friday 29 July 2016

Angular JS Directive For Decimal Places

Here is a simple example for creating an Angular JS Directive.  In this particular case the input is limited to two decimal places but other code could be created here to limit the input in other ways.

Angular Directive

The directive is in javascript and needs to be imported into the page.

(function() {
    'use strict';

    angular.module('myApp').directive('limitedDecimalPlaces',['$filter', function ($filter) {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {

            if (!ngModelCtrl) return;

            function round(value)
            {
                return Math.floor(value * 100) / 100;
            }

            ngModelCtrl.$parsers.push(function (value) {
            var cleanValue = value;
                if (value != value.toFixed(2))
                {
                    cleanValue = (value) ? round(value) : value;
                    ngModelCtrl.$setViewValue(cleanValue.toString());
                    ngModelCtrl.$render();
                }
                return cleanValue;
            });
        }
    };
}]);
})();

The ngModelCtrl is the model controller for this angular input.
$parsers is an array of the parsers that are applied to this input.  $parsers.push adds the function to the array (push is a standard Arrays.push() javascript function)

ngModelCtrl.$setViewValue(...) sets the value into the view part and must be a string.  Overall the function rounds the number to two decimal places if necessary and assigns it to the cleanValue.  This is then set into the view and returned so that the model is updated.  Whatever is returned from this function is what is set into the model.

Usage

The standard input can have this directive added to it so that the validation is wired into the input.

    <input type="number" name="myNumber" ng-model="myNumber" limited-decimal-places>

No comments:

Post a Comment