2015-07-21 75 views
0

我使用下面的代碼來獲取「自動標籤」與AngularJS工作(自動選項卡上的用戶在「標題」文本框的最大長度爲滿足「名稱」文本框後):麻煩與AngularJS自動標籤

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(); 
     } 
     }); 
    } 
    } 
}]); 

這是我的HTML(我的自定義指令):

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

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

你碰巧知道我做錯了什麼?

回答

1

這段代碼應該這樣做。讓我們儘可能地簡單。 :)

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/

+0

你太棒了!這個解決方案完美無缺 – JD06

+0

semeone粘貼內容時如何使其工作? – alexislg

1

你的第一個錯誤是你的標籤是錯誤的使用指令。應該

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

指令應改爲:

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(); 
     } 
     }); 
    } 
    } 
}]); 

而且,你沒有你的第二個元素的ID,這樣就不會找到它:

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

working plunker

+1

這也適用!謝謝! – JD06