2014-10-06 92 views
0

我有一個窗體,要求兩個字段中的至少一個有一個值才能生效。現在我已經構建了一個指令'keywordAndOrAuthor'來處理對此的驗證。我設法讓它能夠正確地檢查任何一個字段是否有值,如果是這樣,則將驗證設置爲true。我不知道如何做的是將其他字段的驗證設置爲true。以下是該指令的當前代碼:角度和/或自定義驗證

angular.module('dashboard').directive 'keywordAndOrAuthor', -> 
require: "ngModel" 
link: (scope, elem, attrs, ctrl) -> 
    ctrl.$setValidity 'keywordAndOrAuthor', false 
    ctrl.$parsers.unshift (viewValue) -> 
     siblingElem = elem.siblings('.keyword, .author')[0] 
     if viewValue || siblingElem.value 
      ctrl.$setValidity 'keywordAndOrAuthor', true 
      viewValue 

如何將siblingElem的有效性設置爲true?

** 編輯 **

下面是我想要一個可行的解決方案。

$scope.keywordOrAuthor = (topic_source) -> 
    if (topic_source.authors || topic_source.keywords) then false else true 

關鍵點意識到的是,NG-所需的工作原理類似於角納克級或NG-禁用,如果在正被評估爲真,條件是它僅增加所需的屬性的元素。換句話說,在上面的例子中,如果authors參數或關鍵字參數有值,那麼函數(在ng-require指令內使用)將返回false,並且不會返回驗證錯誤。

回答

1

嘗試設置NG-必須是「如果其他字段爲空」

 <input type="text" ng-model="keyword" ng-required="author === undefined"> 
     <input type="text" ng-model="author" ng-required="keyword === undefined"> 

然後,我不知道你需要的任何指令。

+0

你不能在角度模板中使用===。此外,檢查該字段是否具有「ng-required =」author「'和'ng-required =」關鍵字「''值會更簡單。 – TheSharpieOne 2014-10-06 21:24:54

+0

等等,是否可以包含Ng-require =「author || keyword」來獲得我想要的表單行爲?如何將這種行爲提取到指令中? – 2014-10-06 21:52:07

+0

我不知道在模板中不能做===,只是做==。我一直都在使用它,並且工作正常 – Scott 2014-10-07 00:30:38