我使用以下代码来获取"自动选项卡"使用AngularJS(在" Name"文本框符合最大长度后,自动将用户标记为"标题"文本框):
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>
你碰巧知道我做错了吗?
答案 0 :(得分: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/
答案 1 :(得分: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>
工作plunker