角指令在现有的DOM元素动态设置属性(S) [英] Angular directive to dynamically set attribute(s) on existing DOM elements
问题描述
我有点新的角度,等等各种途径反馈当然欢迎。
I'm somewhat new to Angular, so feedback on alternative approaches is certainly welcome.
我创建了一个名为serverMaxLengths指令。当指令置于NG-形式,它会读取数据库字段从REST API的长度,然后将步行包含表单控制器内的所有投入要素的内容,并设置了最大长度属性的相应。该指令如下:
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) {
...
});
}
};});
这工作。据我了解,$编译正在取代时执行该指令的现有元素(S)。
This works. Insofar as I understand, $compile is replacing the existing element(s) when the directive is executed.
我想知道什么实现这一目标的一个更好的角的方式可能是什么?我想放在任何实际的投入要素(我想要的一切一气呵成发生)的不需要的指令非常简单的解决方案。
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.
推荐答案
的加入$编译(thisElement.contents())(范围);解决这是首要关注的问题。
The addition of $compile(thisElement.contents())(scope); resolved the issue that was of primary concern.
这篇关于角指令在现有的DOM元素动态设置属性(S)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!