0

I have a directive that is designed to be assigned to a normal text input.

<input type="text" ng-model="fooModel" foo-input size="30"
       placeholder="insert value"></input>

I have lots of validation functions for it like testing the precision of the numbers and I use a $parsers to control the value that is submitted.

myApp.directive('fooInput', function () {
    return {
        restrict: 'A',
        require: 'ngModel',

        controller: function ($scope, $element, $attrs) {
                        this.errorMessage = ""
        },
        link: function (scope, element, attrs, ctrl)

         return ctrl.$parsers.push(function (inputValue) {
                var originalVal = element.val();


                if (!testForOverPrecision(numericVal)) {
                    //do something here to set the directive as invalid
                }

                if (originalVal != inputValue) {
                    ctrl.$setViewValue(res);
                    ctrl.$render();
                }
            });

I have 2 questions:

  1. How do I get this to work with the isValid service and do I have to have a controller scope for the error message
  2. Is it correct for me to push the $parser inside a return statement
3
  • if you are using (or can use) angular 1.3 the whole validation API just got a huge improvement and simplification. Makes exactly what you are doing a lot cleaner see: yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html The video is very helpful Commented Sep 16, 2014 at 16:59
  • what version is it now? Commented Sep 16, 2014 at 17:35
  • have no idea what you are using. Date on link is this month, video was I think in august. If intend to work with angular forms much, video is excellent ( angular team member). API wasn't 100% complete then Commented Sep 16, 2014 at 17:37

1 Answer 1

1

I am using Angular 1.2x and I created a directive to determine if the text contains the @ symbol.

.directive('noAt', function() {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function(viewValue) {
                if (/@/.test(viewValue)) {
                    ctrl.$setValidity('noAt', false);
                    return undefined;
                } else {
                    ctrl.$setValidity('noAt', true);
                    return viewValue;
                }
            });
        }
    };
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.