JD06
JD06

Reputation: 191

Trouble with AngularJS auto-tab

I am using the following code to get the "auto tab" working with AngularJS (automatically tabs the user to the "Title" textbox after the max length is met for the "Name" textbox):

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

app.directive('autoTabTo', [function () {
return {
  restrict: "A",
  link: function (scope, el, attrs) {
      el.bind('keyup', function(e) {
        if (this.value.length === this.maxLength) {
          var element = document.getElementById(attrs.autoTabTo);
          if (element)
            element.focus();
        }
      });
  }
  }
}]);

Here is my HTML (with my custom directives):

<customtextfield autoTabTo="Variant.Specs.Title" ng-maxlength="20" customfield="Variant.Specs.Name"></customtextfield>

<customtextfield ng-maxlength="25" customfield="Variant.Specs.Title"></customtextfield>

Would you happen to know what I am doing wrong?

Upvotes: 0

Views: 1733

Answers (2)

logee
logee

Reputation: 5067

Your first error is your markup is wrong for using the directive. Should be

<input auto-tab-to="Variant.Specs.Title" ng-maxlength="4" customfield="Variant.Specs.Name"></input>

Directive should be changed to:

app.directive('autoTabTo', [function () {
return {
  restrict: "A",
  link: function (scope, el, attrs) {
      el.bind('keyup', function(e) {
        if (this.value.length === parseInt(attrs.ngMaxlength)) {
          var element = document.getElementById(attrs.autoTabTo);
          if (element)
            element.focus();
        }
      });
  }
  }
}]);

Also, you don't have an ID on your second element so it won't find it:

<input ng-maxlength="4" customfield="Variant.Specs.Title" id="Variant.Specs.Title"></input>

working plunker

Upvotes: 1

Chong Tang
Chong Tang

Reputation: 2146

This piece of code should do it. Let's keep it as simple as possible. :)

HTML:

<div ng-app="autofocus">
    <label>Name:</label>
    <input ng-model="maxLengthReach"></input>
    <br/><br/>
    <label>Title:</label>
    <input autofocus-when></input>
</div>

Javascript:

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

app.directive('autofocusWhen', function () {
    return function (scope, element, attrs) {
        scope.$watch('maxLengthReach', function(newValue){
            if (newValue.length >= 5 ) {                                                   
                element[0].focus();
            }
        });
    }
});

jsFiddle: http://jsfiddle.net/gctvyfcz/1/

Upvotes: 1

Related Questions