Question

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: abc@gmail.com

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 "abc@gmail.com".

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

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top