2014-02-10 132 views
1

你好,我的驗證指令有問題。首先,我有指令,創建輸入元素,其中我有一個是基於一些參數告訴我們,如果這calidation應該被解僱,或根本沒有指令......它看起來像這樣:Angularjs自定義驗證指令

app.directive('ngAttr', function($compile){ 
return { 
    scope:{}, 
    link: function (scope, element, attrs){ 
     var opts = scope.$eval(attrs.ngAttr); 

     if(opts.condition){ 
      element.attr(opts.attrName, opts.condition) 
     } 
    } 
}; 

}) ;

它增加了屬性基礎上傳遞給它的條件......如果我想有條件地添加指令我做的:

ng-attr="{condition: {{opts.validatePhone}}, attrName:'validate-phone'}" 

爲創建一個輸入屬性恩我以前的指令......而問題是驗證電話指令發射了,只有當該指令被創建,一旦它doen't上輸入處理程序的反應...驗證指令的代碼是:

app.directive('validatePhone', function($compile){ 
return{ 
    require: 'ngModel', 
    link: function(scope, element, attrs, ngModel){ 

     function validate(val){ 
      console.log(val) 
     } 

     scope.$watch(function() { 
      return ngModel.$viewValue; 
     }, validate); 

    } 
}; 

});

不是很簡單,但console.log()在更改輸入時無法工作。

我創建了一個plunker所以它會比較容易檢查,如果有人有一個想法...... http://plnkr.co/edit/CgVCV58goFS9GKLBtRrw?p=preview

+0

確定我記錄了validatePhone指令的範圍,它不是適用於表單輸入指令的範圍,但父範圍嗯爲什麼... –

回答

0

我不相信$手錶功能的設置是否正確。

如果您希望 在帶有驗證功能的指令中做的更具體一些,它將會有所幫助。

以下是$ watch上的Angularjs文檔的鏈接。

[$watch][1] 

請注意手錶表達式是範圍的一個屬性。您不在$ watch功能中包含任何內容。你說的'範圍'請'看'功能。

什麼,你應該說的是

「範圍」,請「手錶」這個屬性被稱爲「在這裏輸入的範圍財產」,當它改變了執行該功能,或者一些其他的自定義邏輯。

我認爲這主要是因爲你沒有看任何東西。你需要觀察你用來更新的任何模型。

你的函數改成這樣......

scope.$watch(attrs.ngModel, function(elementValue) { 
    if(!elementValue){ return; } // return if falsy. 
    if(validate(elementValue)){ return elementValue; } 
    }); // or something like this. 

如果你不知道每個NG-模式的價值,因爲也許他們正在使用NG重複動態創建,並從服務器未知值你可以做這樣的事情來觀看一些事情。

app.directive('mydirective', function(){ 

    return { 
    restrict:'A', // Declares an Attributes Directive. 
    require: '?ngModel', // ? checks for parent scope if one exists. 

    link: function(scope, elem, attrs, ngModel){ 
     if(!ngModel){ return }; 

     scope.$watch(attrs.ngModel, function(value){ 
     if(!value) { return }; 
     // do something with validation of ngModel. 
     }); 
    } 
    } 
}); 

然後在你的HTML

<input type="text" ng-model="{{ dynamicValue }}" my-directive /> 

<input type="text" ng-model="{{ dynamicValue }}" my-directive="myFunctionName()" /> 

你將不得不一點點添加到指令,但運行的功能。 可能像隔離

scope: { 
    myDirective: '&' 
} 

範圍然後在指令$手錶,你可以像

scope.myDirective(); 

像這樣的事情,我認爲運行它。

此外,有很多方法來驗證使用Angularjs。這是另一個鏈接。

Here is one way

有幾種方法來連接驗證。

你可以看$它的模型, 您可以添加功能火上的一些事件(模糊,點擊,焦點等) 或者只是運行功能時,該指令加載由剛調用你的驗證功能驗證(值);