簡體   English   中英

為標簽和屬性組合創建自定義的角度指令?

[英]Creating a custom angular directive for tag and attribute combination?

好的,這是交易。

我為input標簽創建了一個自定義指令,並為input[type=ip]進行了自定義驗證:

.directive('input', function($q, $timeout) {
    return {
        restrict: "E",
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            if (attrs.type !== 'ip') return;
            var reg = new RegExp("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
            ctrl.$asyncValidators.ip = function(modelValue, viewValue) {
                if (ctrl.$isEmpty(modelValue)) {
                    return $q.when();
                }

                var def = $q.defer();
                if(reg.exec(modelValue)) {
                    def.resolve();
                } else {
                    def.reject();
                }

                return def.promise;
            };
        }
    };
});

這非常有效,我計划將來使用它來創建自定義驗證。

我遇到的問題是input[type=file] 在視圖中,它沒有ngModel屬性。 Angular不喜歡這樣。 從技術上講,它是一個input標簽,因此它可以解釋input指令...但是需要ngModel屬性。

我怎樣才能解決這個問題? 如何基於不會相互破壞的type屬性創建自定義input指令?

我可以提出require: 'ngModel'以某種方式進行選擇嗎?

菲爾(Phil)使用?ngModel的評論修正了它。 一切正常。

暫無
暫無

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

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