1
我有一個包含我想要驗證的自定義指令的表單。如果範圍不是孤立範圍,我可以這樣做,但如果我們有孤立範圍的情況下如何繼續? Here是一個窗體包含2個字段的例子:名字和姓氏。名字直接在表格上,但姓氏在指令內。當我點擊'保存'時,只有名字被驗證。有人能指出我錯過了什麼嗎?代碼都有點像這樣:驗證表單中的自定義指令
主要形式有:
<form class=" form form-group" name="personForm" ng-submit="saveInfo(personForm.$valid, '#/success')" novalidate>
<label for="fname"><strong>First Name:</strong></label>
<input type="text"
name="fname"
class="form-control"
ng-model="person.firstname"
ng-maxlength=10
ng-minlength=3
ng-required="true">
<div class="error-message" ng-messages="personForm.fname.$error" data-ng-if="interacted(personForm.fname)">
<div ng-message="required">This is a required field</div>
<div ng-message="maxlength">max length should be 10</div>
<div ng-message="minlength">min length should be 3</div>
</div>
<last-name ng-model="person"></last-name>
<br/>
<button class="btn btn-primary" type="submit">Save</button>
和指令(姓):
<label for="lname"><strong>Last Name:</strong></label>
<input type="text"
name="lname"
class="form-control"
ng-model="person.lastname"
ng-maxlength=20
ng-minlength=5
ng-required="required">
<div ng-messages="personForm.lname.$error" data-ng-if="interacted(personForm.lname)">
<div ng-message="required">This is a required field</div>
<div ng-message="maxlength">max length of last name should be 20</div>
<div ng-message="minlength">min length of last name should be 5</div>
</div>
...終於在這裏是我的javascript:
var app = angular.module('MyApp',['ngRoute','ngMessages']);
app.config(function ($routeProvider) {
$routeProvider
.when('/success', {
templateUrl: 'success.html'
})
.when('/', {
templateUrl: 'first-name.html',
controller: 'MyController'
})
})
app.directive('lastName', function() {
return {
restrict: 'E',
scope: {
person: '=ngModel',
},
require:'ngModel',
templateUrl: 'last-name.html'
}
});
app.controller('MyController', function($scope, $location) {
$scope.person = {};
$scope.submitted = false;
$scope.interacted = function(field) {
return $scope.submitted || field.$dirty;
};
$scope.saveInfo = function(isValid, url) {
$scope.submitted = true;
if (isValid) {
$location.path(url);
} else {
alert('Missing values in mandatory fields');
}
}
});