【发布时间】:2014-02-12 02:48:03
【问题描述】:
我对 Angular 有点陌生,因此当然欢迎对替代方法提供反馈。
我创建了一个名为“serverMaxLengths”的指令。当指令放置在 ng-form 上时,它将从 REST API 获取数据库字段长度,然后遍历表单控制器中包含的所有输入元素的内容,并相应地设置“maxlength”属性。指令如下:
myApp.directive('serverMaxLengths', function ($log,$http,$compile) {
return {
restrict: 'A',
require: '^form',
link: function (scope, elem, attrs, formController) {
if (!formController) return;
var httpConfig = {
method: 'GET',
url: myAppRestURL + "/validator-rest?action=getDBFieldLengths"
};
$http(httpConfig)
.success(function (data, status, headers, config) {
if (typeof data.isValid != 'undefined') {
if(data.isValid){
var inputElem = elem.find('input');
angular.forEach(inputElem, function (value, key) {
var thisElement = angular.element(value);
if (typeof thisElement[0] !== 'undefined') {
if(typeof data.dbFieldLengths[thisElement[0].id] !== 'undefined'){
if(data.dbFieldLengths[thisElement[0].id] > 0){
thisElement.prop("maxlength", data.dbFieldLengths[thisElement[0].id]);
thisElement.prop("ng-maxlength", data.dbFieldLengths[thisElement[0].id]);
thisElement.prop("ng-minlength", 0);
$compile(thisElement)(scope);
}
}
}
});
}else{
...
}
}else{
...
}
}).error(function (data, status, headers, config) {
...
});
}
};});
这行得通。据我了解, $compile 正在执行指令时替换现有元素。
我想知道实现这一目标的更好的“Angular”方式是什么?我想要一个非常简单的解决方案,不需要将指令放在任何实际输入元素上(我希望一切都在一次发生)。
最后,设置最大长度的字段之一分配了一个 UI Bootstrap Typeahead 指令。在应用“maxlength”之前,该指令按预期工作。但是,通过上述方法在字段上设置“maxlength”后应用,当输入失去焦点时,提前输入会呈现“TypeError: Cannot read property 'length' of undefined”错误(否则它可以工作)。这让我对这种方法以及幕后发生的事情感到担忧。
*注意:提前输入错误通过以下方式解决:
$compile(thisElement.contents())(scope);
代替:
$compile(thisElement)(scope);
感谢您的任何反馈/建议/想法。
【问题讨论】:
标签: javascript angularjs angular-ui-bootstrap