Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic value in ng-minlength

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:

enter image description here

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?

like image 200
jviotti Avatar asked Nov 09 '13 18:11

jviotti


2 Answers

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">
like image 172
Ilan Frumer Avatar answered Nov 15 '22 21:11

Ilan Frumer


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']
like image 31
Zack Yang Avatar answered Nov 15 '22 22:11

Zack Yang