簡體   English   中英

Angular指令可在現有DOM元素上動態設置屬性

[英]Angular directive to dynamically set attribute(s) on existing DOM elements

我是Angular的新手,因此歡迎您提供有關替代方法的反饋。

我創建了一個名為“ serverMaxLengths”的指令。 將指令放在ng-form上時,它將從REST API中獲取數據庫字段的長度,然后遍歷form控制器中包含的所有輸入元素的內容,並相應地設置“ 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替換了現有元素。

我想知道實現這一目標的更好的“角度”方式是什么? 我想要一個非常簡單的解決方案,不需要將指令放置在任何實際的輸入元素上(我希望一切都一次性完成)。

最后,獲得最大長度設置的字段之一分配了一個UI Bootstrap Typeahead指令。 在應用“ maxlength”之前,該指令可以按預期工作。 但是,通過上述方法在字段上應用“ maxlength”設置后,當輸入失去焦點時,前面的類型將引發“ TypeError:無法讀取屬性的'length'of undefined”錯誤(否則它將起作用)。 這讓我擔心這種方法以及幕后發生的事情。

*注意:通過執行以下操作可以解決類型超前錯誤:

$compile(thisElement.contents())(scope);

代替:

$compile(thisElement)(scope);

感謝您的任何反饋/建議/想法。

$ compile(thisElement.contents())(scope)的添加; 解決了最主要的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM