My goal is to enhance the flexibility of my service by enabling it to handle any input field dynamically. Currently, I find myself manually coding everything, which is becoming quite labor-intensive. Is there a way to pass the element object when the elements ng-change property is triggered? This way, I can update the elements ng-class accordingly.
Example HTML:
<input type="text" id="email" data-ng-model="email" data-ng-change="changeEmail()" placeholder="your email here" data-ng-class="emailFormControlColor">
In the controller:
$scope.changeEmail = function () {
if ($checkInput.checkEmail($scope.email)) {
// email input is valid
$scope.emailFormControlColor = 'form-control-success'; // update class to success
} else {
// email input is invalid
if ($scope.emailFormControlColor === 'form-control-success')
$scope.emailFormControlColor = 'form-control-error'; // update class to error
}
};
The service (included in the controller arguments):
.service('checkInput', ['$controller', '$window', '$location', function ($controller, $window, $location) {
return {
checkEmail: function (email) {
// <--- Here, I aim to update the ng-class of the focused element dynamically! This would eliminate the need for manual coding for each input field!
var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
};
}])
Currently, I am manually updating the $scope.emailFormControlColor. But what if I have multiple input fields:
<input type="text" id="email1" data-ng-model="email1" data-ng-change="changeEmail()" placeholder="your email here" data-ng-class="emailFormControlColor1">
<input type="text" id="email2" data-ng-model="email2" data-ng-change="changeEmail()" placeholder="your email here" data-ng-class="emailFormControlColor2">
<input type="text" id="email3" data-ng-model="email3" data-ng-change="changeEmail()" placeholder="your email here" data-ng-class="emailFormControlColor3">
How can I modify my service to eliminate the need for manual coding like:
$scope.emailFormControlColor1 = 'form-control-success';
$scope.emailFormControlColor2 = 'form-control-success';
$scope.emailFormControlColor3 = 'form-control-success';
I hope my query is clear. If not, please let me know and I will clarify!