2013-09-30 29 views
22
link: function(scope, elm, attrs, ctrl) { 
     ctrl.$parsers.unshift(function(viewValue) { 

      scope.pwdValidLength = (viewValue && viewValue.length >= 8 ? 'valid' : undefined); 
      scope.pwdHasLetter = (viewValue && /[A-z]/.test(viewValue)) ? 'valid' : undefined; 
      scope.pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? 'valid' : undefined; 

      if(scope.pwdValidLength && scope.pwdHasLetter && scope.pwdHasNumber) { 
       ctrl.$setValidity('pwd', true); 
       return viewValue; 
      } else { 
       ctrl.$setValidity('pwd', false);      
       return undefined; 
      } 

     }); 
    } 

http://jsfiddle.net/adamdbradley/Qdk5M/

在上面提到的小提琴怎樣的密碼驗證發生? $ parser.unshift做什麼?以及test(viewValue).....的用法是什麼? 我已經提到AngularJs主的網站,但無法理解任何東西...... 請指引我一步它是如何驗證的步驟......

我是新來angularJS ..

回答

60

下面是一個一步一步的解釋。請注意,文檔非常好:the formsthe $parsers上的頁面是您正在尋找的頁面。

link: function(scope, elm, attrs, ctrl) { 
    /** 
    * This function is added to the list of the $parsers. 
    * It will be executed the DOM (the view value) change. 
    * Array.unshift() put it in the beginning of the list, so 
    * it will be executed before all the other 
    */ 
    ctrl.$parsers.unshift(function(viewValue) { 

     scope.pwdValidLength = (viewValue && viewValue.length >= 8 ? 'valid' : undefined); // Check the length of the string 
     scope.pwdHasLetter = (viewValue && /[A-z]/.test(viewValue)) ? 'valid' : undefined; // Check if the string contains letter. RegExp.test() simply returns a boolean if the string matches the regex. 
     scope.pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? 'valid' : undefined; // Check if the string contains digit. Same remark. 

     if(scope.pwdValidLength && scope.pwdHasLetter && scope.pwdHasNumber) { // If all is good, then… 
      ctrl.$setValidity('pwd', true); // Tell the controlller that the value is valid 
      return viewValue; // Return this value (it will be put into the model) 
     } else { // … otherwise… 
      ctrl.$setValidity('pwd', false); // Tell the controlller that the value is invalid 
      return undefined; // When the value is invalid, we should return `undefined`, as asked by the documentation 
     } 

    }); 
} 
+1

偉大的答案。應該被接受。 – hitokiri82

+0

需要說明的是,$ parsers是一個數組(意思是標準的javascript類型,並非特定於Angular)。 unshift是Javascript Array原型的一種本地方法,因此「Array.unshift()」的答案中的評論將它放在列表的開頭......「 這是一個重要的區別,我認爲,因爲初學者可能會感到困惑什麼是角度,什麼是本地JS。 – dudewad