<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>test表单验证</title>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('testCtrl', function($scope) {
var _test = function() {
$scope.canSubmit = false;
console.log('a');
};
var init = function() {
$scope.model = {
name: 'happen'
};
$scope.canSubmit = true;
$scope.test = _test;
};
init();
});
app.directive('testValid', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
var init = function() {
elem.on('blur', function() {
scope.$apply(function() {
if (elem.val() === 'happen') {
ctrl.$setValidity('isHappen', false);
} else {
ctrl.$setValidity('isHappen', true);
}
});
});
};
init();
}
}
});
</script>
</head>
<body>
<form name="myForm">
<div ng-controller="testCtrl">
<input type="text" name="test" ng-model="model.name" test-valid required>
<p ng-show="myForm.test.$error.isHappen">名字是默认值</p>
<p ng-show="myForm.test.$error.required">名字必填项</p>
<button ng-disabled="myForm.$invalid || !canSubmit" ng-click="test();" style="width: 200px;height: 20px;"></button>
</div>
</form>
</body>
</html>