I'm a bit perplexed when it comes to validation in angular. It seems like all of the validation is connected to the form. But what happens when the controller needs to ascertain if the model is valid or not?
Here's an example I quickly whipped up:
HTML
<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>
JavaScript
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 can I check for 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);
}
});
Link to Fiddle
My challenge lies in getting the valid()
function to accurately determine whether the data in the model is valid or not. I've attempted using journeyForm.$valid
, $scope.journeyForm.$valid
, and
$scope.journeyFormDepartureAirport.$valid
, but none seem to work.
I'm struggling to figure out how to access $valid
from within my controller. Particularly since there are a variable number of forms.
Is it appropriate for the controller to have knowledge of the forms? Isn't that more of a view concern?
It appears that all the validation is concentrated within the view, leading me to believe that angular lacks the concept of an invalid model. It simply sees the data as just that. However, this poses a problem for me as I need to ensure that the model meets all criteria specified in the view, such as ng-required
, prior to executing an action in the controller.