jviotti
jviotti

Reputation: 18949

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?

Upvotes: 8

Views: 4016

Answers (3)

S&#248;ren
S&#248;ren

Reputation: 23921

It is not difficult to achieve a dynamic value of ng-minlength. Angular will watch $scope values and update accordingly.

See a Plunker: http://plnkr.co/edit/tMHQq7YIBlvMw7A60H2e?p=preview

Controller

function myCtrl (){
   $scope.myMinLength = 5; // could also come from config
}

View:

<input type="text" ng-model="myString" ng-minlength="myMinLength">

The important thing to note, is that the value of ng-minlength does not have to be in braces.

Upvotes: 0

Ilan Frumer
Ilan Frumer

Reputation: 32377

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">

Upvotes: 8

Zack Yang
Zack Yang

Reputation: 399

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']

Upvotes: 1

Related Questions