我对角度验证有点困惑。所有验证似乎都与表单绑定。但是,如果控制器需要知道模型是否有效,你会怎么做?
我已经打破并举例:
<div ng-app="stpApp">
<div id="multiStop" class="fullBottomContent" ng-controller="multiStopController">
<ul class="journey">
<li ng-repeat="journey in inboundJourney">
<ng-form name="journeyForm">
<span>
<input type="text" class="AirportName" name="DepartureAirport" ng-model="journey.DepartureAirport" ng-required="true" />
<span ng-show="journeyForm.DepartureAirport.$error.required">Invalid</span>
</ng-form>
<a class="removeJourney" ng-click="removeInboundJourney($index)" href="javascript:void(0)">Remove</a>
</li>
</ul>
<span ng-show="valid()">this is all valid</span>
<span ng-click="addInboundJourney()" title="Add a journey">+</span>
</div>
</div>
var stpApp = angular.module('stpApp', []);
stpApp.controller('multiStopController', function ($scope, $compile, $http) {
$scope.showAddButton = true;
$scope.dataLoaded = false;
$scope.inboundJourney = [
{ 'DepartureAirport': '',
'DestinationAirport': '',
'DepartureDate': '',
'DepartureTime': '9',
'Class': 'All'
},
{ 'DepartureAirport': 'Test1',
'DestinationAirport': '',
'DepartureDate': '',
'DepartureTime': '9',
'Class': 'All'
}
];
$scope.valid = function() {
//how do I test validity here?
return true;
}
$scope.addInboundJourney = function () {
$scope.inboundJourney.push({ 'DepartureAirport': '',
'DestinationAirport': '',
'DepartureDate': '',
'DepartureTime': 9,
'Class': ''
});
}
$scope.removeInboundJourney = function (index) {
$scope.inboundJourney.splice(index, 1);
}
});
所以我希望我的valid()
函数返回true或false,具体取决于模型中的数据是否有效。我试过了journeyForm.$valid
,$scope.journeyForm.$valid
和$scope.journeyFormDepartureAirport.$valid
。这些都不起作用。
我无法弄清楚如何从我的控制器中检查$valid
。特别是因为我有可变数量的表单。
控制器是否应该知道表格?那是在视图中?
我认为问题在于验证都在视图中。我猜这个角度没有无效模型的概念。这只是数据。但是,嗯,这对我来说是一个问题。我想知道模型符合我的所有标准(添加到视图中,例如ng-required
)之前我在控制器中执行操作。
答案 0 :(得分:1)
使用$valid
<form name="myform" >
<input type="text" name="input1" ng-required="true"/>
....
JS
$scope.valid = function() {
return $scope.myform.$valid; /* how to return $valid for 'myform' form */
}
答案 1 :(得分:1)
我明白了,Rob实际上帮了很多。我的问题是表格的放置:
<li ng-repeat="journey in inboundJourney">
<ng-form name="journeyForm">
Angular似乎不喜欢ng-repeat
中的表单。我改成了:
<ng-form name="journeyForm">
<ul class="journey">
<li ng-repeat="journey in inboundJourney">
即。表格在ng-repeat
之外,然后像Rob建议的那样,
$scope.valid = function() {
return $scope.journeyForm.$valid; /* how to return $valid for 'myform' form */
}
这一切都有效
呻吟一下,这并没有抱怨语法无效。从我有限的角度经验来看,这是一个不变的问题,它有一种令人讨厌的习惯,就是默默地失败。 Needz moar error pleaz
答案 2 :(得分:1)
您可以使用$watch
$scope.valid = false;
$scope.$watch('inboundJourney', function(){
var isValid = false;
//set isValid depending on inboundJourney
$scope.valid = isValid;
});
然后将其设置为显示条件
<span ng-show="valid">this is all valid</span>