I have a constant called Config
which contains a task.minlength = 3
attribute.
I'm appending the constant in the $rootScope
:
.run(function($rootScope, Config) {
$rootScope.Config = Config;
})
From within a template, I want to set Config.task.minlength
value into an input's ng-minlength
directive:
<input type="text" ng-model="newTask" placeholder="Write a new task..." required ng-minlength="{{ Config.task.minlength }}">
Which gets correctly parsed according to DevTools:
However, validation doesn't gets triggered:
$scope.form.$error['minlength'] // undefined
It works fine when I just write 3
instead of interpolating Config.task.minlength
.
Does the value of ng-minlength
has to be hardcoded? Is there any workaround?
ngModelController
do not $observe or $eval the value of ngMinlength
in any way, therefore It only gets static integer values.
I created my own directive which use $observe
,
Here is an example:
app.directive('myMinlength',function(){
return {
require: 'ngModel',
link: function(scope,elm,attr,ngModel){
var minlength = 0;
var minLengthValidator = function(value){
var validity = ngModel.$isEmpty(value) || value.length >= minlength;
ngModel.$setValidity('minlength', validity);
return validity ? value : undefined;
};
attr.$observe('myMinlength', function(val){
minlength = parseInt(val,10);
minLengthValidator(ngModel.$viewValue);
});
ngModel.$parsers.push(minLengthValidator);
ngModel.$formatters.push(minLengthValidator);
}
};
});
Use it like so:
<input type="text" name="something" my-minlength="{{config.min}}" ng-model="something">
Oh, there some syntax errors.
You should set a name for input:
<input name="newtask" type="text" ng-model="newTask" placeholder="Write a new task..." required ng-minlength="{{ Config.task.minlength }}">
Then, you will catch the error like this:
$scope.form.newtask.$error['minlength']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With