Prokurors
Prokurors

Reputation: 2548

Field is undefined when fails to meet ng-maxlength requirement

I'm new to AngularJs/Web stuff, seems it should be basic stuff but I struggle to find solution to this problem...

I have a ModalWindow in which user can enter a comment. In case if this comments exceeds X number of characters Saving should be prevented (+some error message). So I thought ng-maxlength directive should do the trick, but it behaves strangely.

When length requirement is passed, then $scope.fieldName contains data (which is as expected), but in case if user enters more than allowed characters - then $scope.fieldName is undefined and trying to access field's $error field throws an exception.

From what I've seen in this case field's $error.maxlength should have been set instead...

So any ideas, suggestions on how to fix this?

//in View

    <div class="display-field notator-holder">
        <textarea class="notator"
                  cols="20"
                  id="something"
                  name="fieldName"
                  ng-model="fieldName"
                  ng-maxlength="14"
                  rows="5" hidden>
        </textarea>
    </div>

//...in Controller

$scope.saveChanges = function () {
    if ($scope.fieldName.$error.maxlength) 
    ...
}

Upvotes: 1

Views: 635

Answers (2)

Immanuel Kirubaharan
Immanuel Kirubaharan

Reputation: 1094

Try using only maxlength instead of ng-maxlength which will restrict user to enter more than the given limit to it as shown in this plunker.

Template:

<textarea class="notator" cols="20" id="something" name="textArea" 
      ng-model="fieldName" maxlength="14" rows="5"></textarea>
<p ng-show="meForm.textArea.$error.maxlength">Oi! Too long matey!</p>
<p>Value = {{fieldName ? fieldName : "Invalid/Nothing"}}</p>
<p>{{meForm.textArea}}</p>

Upvotes: 0

Alok
Alok

Reputation: 1310

It is behaving as expected. What you are missing is, you need to access the form items from form. Model value defaults to nothing when there is nothing ie. when there's an error in validation.

Here's an example.

var app = angular.module('app', []);

app.controller('ctrl', function($scope) {
});
<script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <div ng-app="app" ng-controller="ctrl">
  <form name="meForm">
    <textarea class="notator" cols="20" id="something" name="textArea" ng-model="fieldName" ng-maxlength="14" rows="5">
    </textarea>
    <p ng-show="meForm.textArea.$error.maxlength">Oi! Too long matey!</p>
    <p>Value = {{fieldName ? fieldName : "Invalid/Nothing"}}</p>
    <p>{{meForm.textArea}}</p>
  </form>
</div>

Upvotes: 2

Related Questions