Through the use of AngularJS, I've developed a directive called "integer" that invalidates a form if anything other than integers are entered. Because I'm generating the page dynamically by fetching data from the database, it would be helpful to specify the type of validation as a variable and utilize this variable as the directive, which could be for integers, doubles, etc. To gain a better understanding, please refer to the following Plunker: http://plnkr.co/edit/QEqEexCzSDnUuuhnYpbN?p=preview
<form name="dynamicForm" ng-controller="Controller" ng-submit="applyConfiguration()">
<my-customer info="component" name="{{dynamicName}}" ng-model="password" {{dynamicValidate}}></my-customer>
<span class="error" ng-show="dynamicForm.{{dynamicName}}.$error.{{dynamicValidate}}">Not valid number!</span>
<hr>
<input type="submit" value='Apply'>
</form>
(function(angular) {
'use strict';
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };
$scope.persons = [$scope.naomi,$scope.igor];
$scope.password = "first password";
$scope.component = 'text';
$scope.dynamicName = 'testName';
$scope.dynamicValidate = 'integer';
$scope.applyConfiguration = function(){
alert($scope.password);
}
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
info: '=',
ngModel: '='
},
template: function(elem,attr){
//var template = 'Name: {{info.name}} Address: {{info.address}}';
var template = '<input type="{{info}}" name="fname" ng-model = "ngModel">';
//elem.html(template);
return template;
}
};
}).directive('integer', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var validator = function (value) {
//var num = parseFloat(value);
if(/^(\-|\+)?([0-9]+(\[0-9]+)?|Infinity)$/.test(value)){
ngModel.$setValidity('integer',true);
return value;
}else{
ngModel.$setValidity('integer',false);
return value;
}
};
ngModel.$parsers.unshift(validator);
ngModel.$formatters.unshift(validator);
}
};
});
})(window.angular);
Instead of using the attribute "integer," I aim to assign the already initialized variable dynamicValidate, set as "integer" in the controller. Best regards, Mukthi