0

I'm in the process of converting AngularJS to Angular 6. How do I convert this directive to work with Angular 6?

app.directive('numberOnly', function() {
return {
    priority: 1, // if we're unshifting, lower number priority runs later; if we're pushing, lower number priority runs earlier
    require: 'ngModel', // element must have ng-model attribute.
    restrict: 'A', // restrict to an attribute type.
    // scope = the parent scope
    // elem = the element the directive is on
    // attr = a dictionary of attributes on the element
    // ctrl = the controller for ngModel.
    link: {
        pre: function (scope, elemn, attr, ctrl) {
            var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
            var testNumber = function (value) {
                var empty = ctrl.$isEmpty(value); // nifty built-in method to do null/undefined/'' checks

                if (empty) {
                    return true; // returning true avoids a false positive on $error since $setValidity inverts it.
                }
                return NUMBER_REGEXP.test(value);
            }
            ctrl.$parsers.unshift(function (value) {
                // test the validity after update.
                var valid = testNumber(value);
                // set the validity after update.
                ctrl.$setValidity('numberOnly', valid);

                // if it's valid, return the value to the model, otherwise return undefined.
                return valid ? value : undefined;
            });
            ctrl.$formatters.unshift(function(value) {
                // test the validity after update.
                var valid = testNumber(value);
                // set the validity after update.
                ctrl.$setValidity('numberOnly', valid);
                return value;
            });
        }
    }
};
});

Is it possible to add more functions in single directive?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
CoolKane
  • 43
  • 1
  • 2
  • 8
  • 1
    What did you try? – Jeroen Heier Jun 04 '18 at 18:17
  • I'm confused with **function (scope, elemn, attr, ctrl)** not sure what that does. Also I'm new to coding – CoolKane Jun 04 '18 at 18:43
  • You can either [create your own validator functions](https://angular.io/guide/form-validation#custom-validators) or [use the functions from Angular's `Validators` class](https://angular.io/api/forms/Validators). – georgeawg Jun 04 '18 at 20:56

0 Answers0