是否可以将参数从ng-pattern(html输入)传递给AngularJs工厂? 目前,我有一个自定义工厂 validateFormFieldFactory 。并且将为每个控制器注入自定义工厂/服务。
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>
我们的想法是将工厂用于整个应用(可重复使用的工厂)。 它可以是工厂,服务,提供商或指令。目前我还没有找到任何关于如何做这种魔术的例子,但如果我可以使用ng-pattern和服务指定firstName,LastName或email等,那将非常有用。这样的事情可能会有所帮助 - Example2