Creating Advanced Forms
Template:
<form novalidate ng-controller="MainCtrl" name="userForm">
<label>Websites</label>
<div ng-show="userForm.$invalid">The User Form is invalid.</div>
<div ng-repeat="website in user.websites" ng-form="websiteForm">
<input type="url" name="website"
ng-model="website.url" required>
<button ng-click="remove($index)">X</button>
<span ng-show="showError(websiteForm.website, 'url')">
Pleae must enter a valid url</span>
<span ng-show="showError(websiteForm.website, 'required')">
This field is required</span>
</div>
<button ng-click="addWebsite()">Add Website</button>
</form>
Controller:
app.controller('MainCtrl', function($scope) {
$scope.showError = function(ngModelController, error) {
return ngModelController.$error[error];
};
$scope.user = {
websites: [
{url: 'http://www.bloggs.com'},
{url: 'http://www.jo-b.com'}
]
};
});
Try it at http://bit.ly/14i1sTp.
Here, we are applying the ngForm directive to div, to create a nested form, which is
repeated for each website in the array of websites on the scope. Each of the nested
forms is called websiteForm and each input in the form is called website. This
means that we are able to access the validity of the ngModel for each website from
within the ngRepeat scope.
We make use of this to show an error message when the input is invalid. The two
ng-show directives will show their error messages when the showError function
returns true. The showError function checks the passed in ngModelController
to see if it has the relevant validation entry in the $error field. We can pass
websiteForm.website to this function since this refers to the ngModelController
object for our website input box.