簡體   English   中英

AngularJS指令無法通過JavaScript添加

[英]Angularjs directive not work to added by javascript

當我通過click事件添加此元素時,我想正常使用我的指令。

我檢查了原始聲明的代碼是否按預期工作。

這個html元素是由javascript函數在被稱為某些click事件時添加的

<input type="text" reg="'^[-+]?([0-9]|[0-8][0-9]|9[0])$'" reg-check>

這是我的指令代碼

TEST.directive('regCheck', function(){
    return {
        restrict : 'A',
        scope: {
            reg : '='
        },
        link : function(scope, element, attrs){
            var regEx = new RegExp(scope.reg);
            var previousValue;
            console.log(regEx);
            $(element).on('keyup' ,function(){
                var dInput = element[0].value
                console.log(dInput);
                if(regEx.test(dInput) || dInput =='' || dInput =='-') previousValue = dInput
                else element[0].value = previousValue
            });
        }
    }
})

我認為此問題的工作原理是jquery事件未呈現到添加的元素。 所以我嘗試

$(document).on('keyup', element ,function(){
     var dInput = element[0].value
     console.log(dInput);
     if(regEx.test(dInput) || dInput =='' || dInput =='-') previousValue = dInput
     else element[0].value = previousValue
});

它也不行。 我該怎么辦?

我認為您無法在keyup事件上觸發指令?

$沒有定義。 簡單的mod可以助您一臂之力:

app.directive('regCheck', function(){
  return {
    restrict : 'A',
    require: 'ngModel',
    scope: {
        reg : '='
    },
    link : function(scope, element, attrs, ngModel){
        var regEx = new RegExp(scope.reg);
        var previousValue;
        console.log(regEx);
        element.on('keyup' ,(ngModel) => {
            console.log('value', ngModel.target.value);
            var dInput = element[0].value
            console.log(dInput);
            if(regEx.test(dInput) || dInput =='' || dInput =='-') previousValue = dInput
            else element[0].value = previousValue
        });
    }
  }
})

並將ng-model添加到您的輸入中,並且每個keyUp事件的輸入值都會輸出到控制台。

<input type="text" ng-model="inputValue" reg-check reg="'^[-+]?([0-9]|[0-8][0-9]|9[0])$'">

注意:我沒有檢查指令或regEx的邏輯,因為我不認為這是問題所在。

暫無
暫無

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

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