0

i have requirement where i can have a predefined suffix for email, so user just has to enter the first part of the email... so lets say my email id is: [email protected]

so the input would have suffix of gmail.com and user should have to enter only "abc". so what i want to achieve is: for display value should be abc, but for ngModel value should be "[email protected]".

how can i achieve this using directives??

i have basic directive ready:plunker

but not sure how to use, link or compile function to achieve above result

1 Answer 1

2

The solution is using $parsers and $formatter.

Try this directive:

app.directive("csRadioFieldFormat", function() {
  return {
    require: 'ngModel',

    restrict: 'A',
    link: function(scope, element, attrs, ctr) {
      ctr.$parsers.unshift(function(value) {

        var isValid = value !== "";

        ctr.$setValidity("required", isValid);
        if (!isValid){
          return undefined;
        }

        if (value.indexOf(attrs.suffix) < 0) {
          value = value + attrs.suffix;
        }

        return value;
      });

      ctr.$formatters.unshift(function(value) {
        value = value || "";
        return value.replace(attrs.suffix, "");
      });
    }
  }
});

Apply it to your email field:

<input type="email" name="myfield" ng-required="options.required" ng-model="ngModel" cs-radio-field-format suffix="{{options.suffix}}"/>

DEMO

Sign up to request clarification or add additional context in comments.

7 Comments

thanks a lot for the answer, its exactly working as expected... just one more question: why is the bootstrap styling still showing the field as invalid(red). i think <input type="email" /> is the problem. but i can not make type=text or if i do make type=text then i will have to use the pattern for email validation.. whats the best way out of this?
can you look at this plunk: plnkr.co/edit/2Bn8Pqm8umMXTb4Um6mY?p=preview for some reason the parser is not getting invoked...
@HarishR: for the styling, it's a css problem. Some rules like input:focus:invalid apply based on the current value in the DOM, it's browser behavior. I don't know a way to get around this problem when we use type="email"
@HarishR: the directive with $parsers must be applied directly to the <input type="number">. In your case, your add parsers inside csNumberField, it does not apply to <input type="number"> in your directive's template.
@HarishR: for the type="email" problem. I think you have to validate the field manually and add a class to the input => then style the input based on its class
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.