I'm trying to create a function that will automatically detect if a user has typed '@' symbol and will autocomplete the field with corporate domain. There might be multiple fields on the page that's why I don't want to hardcode theirs models (e.g. $scope.user.email
).
Here' what I got so far:
<input ng-model="user.email" ng-keyup="autocompleteEmail($event);">
And 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";
}
}
Autocompletion works fine but the problem appears as soon as I try to submit the form with this new value - it doesn't take into account mycompany.com domain that I've added automatically. And request that is being sent has user.email = test@
.
How can I achieve this autocomplete functionality with AngularJS?
To make it as generic as possible, you could go with a directive approach. See this 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 there, I created a directive called "complete-email-domain". It takes in the domain and the email and will automatically update the model once the user enters a '@'. This should be completely re-usable and should scope the actual handling of changing the value to the new directive.
Perhaps an improvement would be to just store the domain on the user object and pass along the user to the directive. Then you can just access the "domain" and "email" properties in a very similar fashion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With