I have a custom driective which wraps input with div and adds a label.
<my-input label="My Label" name="myname" ng-model="mymodel" ng-pattern="/^[a-z]+$/">
I want to use optionally all of possible angular directives for input like ng-pattern, ng-minlength etc. Now it looks like this:
app.directive('myInput',[function () {
return {
restrict: "E",
replace: true,
scope: {
ngModel: '=',
name: '@',
ngMinlength: '=',
ngMaxlength: '=',
ngPattern: '@',
label: '@'
},
compile: function(element, attrs){
if(!_.isUndefined(attrs['ngMinlength'])) {
element.find('input').attr('ng-minlength', 'ngMinlength');
}
if(!_.isUndefined(attrs['ngMaxlength'])) {
element.find('input').attr('ng-maxlength', 'ngMaxlength');
}
if(!_.isUndefined(attrs['ngPattern'])) {
element.find('input').attr('ng-pattern', attrs['ngPattern']);
}
},
template: '<div class="form-group">'
+ '<label>{{ label | translate }}</label>'
+ '<div>'
+ '<input type="text" class="form-control input-sm" name="{{ name }}" ng-model="ngModel">'
+ '</div></div>'
};
}]);
The problem is that I want use ng-pattern exactly the same as ng-pattern works in input, so I want to have possibility to use regexp in the ng-pattern and also scope variable with pattern ($scope.mypattern = /^[a-z]+$/; ... ng-pattern="mypattern"
). How to manage this?
I want both working:
1.
<my-input label="My Label" name="myname" ng-model="mymodel" ng-pattern="/^[a-z]+$/">
2.
$scope.myPattern = /^[a-z]+$/
...
<my-input label="My Label" name="myname" ng-model="mymodel" ng-pattern="myPattern">
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…