Full email domain after the @ symbol in an AngularJS element

I am trying to create a function that will automatically detect that the user has typed the "@" character and will automatically fill this field with the corporate domain. There can be several fields on a page, so I don’t want to hardcode their models (for example, $scope.user.email ).
Here is what I got so far:

 <input ng-model="user.email" ng-keyup="autocompleteEmail($event);"> 

And the corresponding controller code:

 $scope.autocompleteEmail = function($event) { if (($event.keyCode === 48 || $event.keyCode === 50) && $event.srcElement.value.slice(-1) === "@") { // @ symbol is typed - completing email $event.srcElement.value += "mycompany.com"; } } 

Autocomplete works fine, but the problem arises as soon as I try to submit a form with this new value - it does not take into account mycompany.com domain, which I added automatically. And the request that is sent has user.email = test@ .

How can I execute this autocomplete function using AngularJS?

+8
javascript angularjs
source share
2 answers

To make this as general as possible, you can go with a directive approach. See Plunker

 myApp.directive('completeEmailDomain', function(){ return { scope: { domain: '@', email: '=' }, restrict: 'E', template: '<input ng-model="email" ng-keyup="autoCompleteEmail($event);" />', link: function($scope, elem, attr) { $scope.autoCompleteEmail = function($event){ console.log($scope.email); if (($event.keyCode === 48 || $event.keyCode === 50) && $event.srcElement.value.slice(-1) === "@") { $scope.email += $scope.domain; } } } }; }); 

In it, I created a directive called "full email address". It accepts the email address in the domain and automatically updates the model as soon as the user enters "@". This should be fully reused and should cover the actual handling of the change in value to the new directive.

Perhaps an improvement would be to simply save the domain in the user object and pass it in accordance with the directive. Then you can simply access the "domain" and "email" properties in a very similar way.

+1
source share

You can pass the user variable as a parameter in a method so that it can be reused:

  <input ng-model="user.email" ng-keyup="autocompleteEmail($event, user);"> 

And take care of this option:

  $scope.autocompleteEmail = function($event, user) { if (($event.keyCode === 48 || $event.keyCode === 50) && $event.srcElement.value.slice(-1) === "@") { // @ symbol is typed - completing email user.email += "mycompany.com"; } 

Try plunker

0
source share

All Articles