问题描述
我对 Angular 有点陌生,因此当然欢迎对替代方法的反馈.
I'm somewhat new to Angular, so feedback on alternative approaches is certainly welcome.
我创建了一个名为serverMaxLengths"的指令.当指令放置在 ng-form 上时,它将从 REST API 获取数据库字段长度,然后遍历表单控制器中包含的所有输入元素的内容,并相应地设置maxlength"属性.指令如下:
I have created a directive called "serverMaxLengths". When the directive is placed on an ng-form, it will fetch database fields lengths from a REST API and then will walk the contents of all input elements contained within the form controller, and will set the "maxlength" attribute accordingly. The directive is as follows:
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 在指令执行时替换现有元素.
This works. Insofar as I understand, $compile is replacing the existing element(s) when the directive is executed.
我想知道实现这一目标的更好的Angular"方式是什么?我想要一个非常简单的解决方案,不需要将指令放置在任何实际输入元素上(我希望一切都一次性发生).
I'm wondering what a better "Angular" way of achieving this might be? I wanted a very simple solution that doesn't require the directive to be placed on any of the actual input elements(I want everything to happen in one go).
*注意:通过执行以下操作来解决提前类型错误:
*Note: The type ahead error is resolved by doing:
$compile(thisElement.contents())(scope);
代替:
$compile(thisElement)(scope);
感谢您的任何反馈/建议/想法.
Thanks for any feedback/suggestions/thoughts.
推荐答案
$compile(thisElement.contents())(scope);解决了首要关注的问题.
The addition of $compile(thisElement.contents())(scope); resolved the issue that was of primary concern.
这篇关于用于在现有 DOM 元素上动态设置属性的 Angular 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!