Is it possible to pass a parameter from ng-pattern(html input) to AngularJs factory? At the moment, I have a custom factory validateFormFieldFactory. And the custom factory/service is going to be injected for each controller with form.
var app = angular.module('app', []);
// // I would like to have something like this
// app.factory('validateFormFieldFactory', function(fieldType) {
app.factory('validateFormFieldFactory', function() {
var objRegExp = {
"firstName": /^[a-zA-Z]*-*$/,
"lastName": /^[1-9]*-*$/,
"eMail": /^[a-z]*-*$/
};
var regexp = /^[a-zA-Z]*-*$/;
// I would like to have something like this
//var regexp = objRegExp[fieldType]; // fx, first name, last name, email and so on
return {
test: function(value) {
return regexp.test(value);
}
};
});
app.controller('CalculatorController', function($scope, validateFormFieldFactory) {
$scope.validateFormFieldFactory = validateFormFieldFactory;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="CalculatorController">
Enter a something:
<input type="url"
class="form-control"
name="pt-test"
ng-model="Website"
ng-maxlength="50"
ng-pattern="validateFormFieldFactory"/>
<!-- // I would like to have something like this -->
<!--ng-pattern="validateFormFieldFactory('firstName')" -->
</div>
</div>
The idea is to use the factory for the whole application(reusable factory). It can be a factory, service, provider or directive. At the moment I haven't found any example how to do this kind of magic, but it would be really helpful if I could just specify firstName, LastName or email and so on using ng-pattern and the service. Something like this maybe helps - Example2