使用anguar js我创建了一个指令"整数"如果你输入除整数以外的任何其他内容,那么表单无效。因为我通过从数据库中获取数据来动态创建页面,我应该能够指定对变量的验证类型并将该变量用作指令,因为验证可以是整数,双等。请看下面的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);
因此,我应该能够将已经初始化的变量dynamicValidate作为&#34;整数&#34;而不是该属性&#34;整数&#34;在控制器中。 感谢致敬, Mukthi
答案 0 :(得分:0)
不是传递整数,而是创建通用指令名称验证并在那里传递所需的验证。
For Instance,
<my-customer info="component" name="{{dynamicName}}" ng-model="password" validation="integer"></my-customer>
并创建一个名为validation
的指令app.directive('validation', [function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
scope.$watch('[' + attrs.ngModel + ', ' + attrs.validation + ']', function(value){
if(value[0]=="integer")
{
//Your logic for integer here
}
}, true);
}
}
逻辑上这是正确的,应该可行, 请试试这个