我有,我想申請特定的驗證基於角形式:嵌套的角自定義驗證屬性
<form name="createProject" novalidate>
<span ng-show="createProject.projectName.$invalid">Please enter a name for the project.</span></br>
<input type="text" ng-model="newProject.project.name" name="projectName" placeholder="Project Name" required>
<div ng-repeat="topic in newProject.project.topics_attributes">
<span>Topic {{$index + 1}}</span>
<input type="text" ng-model="topic.name" placeholder="Topic Name">
<input type="text" ng-model="topic.feed_size">
<div ng-repeat="topic_source in topic.topic_sources_attributes">
<span>Topic {{$parent.$index + 1}} Source {{$index + 1}}</span>
<select ng-model="topic_source.platform" ng-options="platform for platform in platforms" topic-source-required parent="$parent.topic.name">
<option value="">-- platform --</option>
</select>
<input type="text" ng-model="topic_source.keywords" placeholder="Topic Keywords" topic-source-required parent="$parent.topic.name">
<button ng-show="$last" ng-click="addTopicSource($parent.topic)">Add Topic Source</button>
</div>
</div>
<button ng-click="addTopic()">New Topic</button>
<input type="submit" ng-click="addProject()" ng-class="{ disabled: createProject.$invalid }" ng-disabled="createProject.$invalid" value="Add Project">
</form>
<a href="#">Back</a>
在窗體中,一個項目可以有零個或多個主題。每個主題必須至少有一個主題源。基本上,我想創建驗證,檢查是否添加主題(添加被定義爲具有名稱),如果需要它至少有一個topic_source,並輸入與其關聯的平臺和關鍵字字段。
這甚至可能嗎?我對Angular自定義驗證不是很熟悉,所以我不確定如何開始實現這樣的事情。
**上自定義的驗證指令編輯**
最新研究進展:
angular.module('dashboard').directive 'topicSourceRequired', ($parse) ->
require: "ngModel"
link: (scope, elem, attrs, ctrl) ->
topicName = $parse attrs.parent
scope.$watch topicName, (topicName) ->
ctrl.$parsers.unshift checkForExistence if topicName
checkForExistence = (topicSource) ->
if topicSource
ctrl.$setValidity "topicSourceRequired", true
else
ctrl.$setValidity "topicSourceRequired", false
topicSource
好吧,讓這個驗證接近。現在驗證似乎在檢查兩個topic_source字段是否具有與父名稱字段是否具有值無關的值,並且如果字段已輸入然後擦除,topic_source字段只會註冊爲無效。
如何確保checkForExistence函數僅在topicName具有非空字符串值時被調用?其次,我如何確保空白字段無效,而不必修改它們?
我不太明白。你是說要將驗證綁定到模型,然後檢查以確保模型格式正確嗎?它如何知道在哪裏將DOM中的錯誤歸因於? – 2014-09-30 17:01:14
抱歉不完全清楚。我要說的是,您需要了解表單及其包含的輸入如何工作才能進行自定義驗證。 AngularJS在讓你做到這一點方面非常出色,但所有事情都需要時間來學習。我上面發佈的鏈接也許並不是最好的開始 - 在這裏嘗試:https://docs.angularjs.org/guide/forms – Fordio 2014-09-30 19:08:12
好吧,我想我開始瞭解它的工作原理。我使用$ watch構建了一個指令來檢測是否對$ parent作用域(主題)進行了更改,並檢查topic_source字段是否具有值。問題是$ watch似乎只是在最初添加字段時檢查,而檢查值的函數似乎從未運行。我不太清楚如何獲得$ watch來檢查模型的任何變化,以及如何使它調用檢查值函數。 – 2014-09-30 20:32:28