我希望创建一个自定义指令,它呈现为输入类型元素。该指令应该重用 angularjs 验证框架。以下是custom-input
我创建的实际指令:
<!doctype html>
<html ng-app="validationApp">
<body>
<div class="container" ng-controller="ValidationController as validationController">
<form name="myForm">
{{employee | json}}
<custom-input ng-required="true" ng-model="employee.name" name="employee.name" id="employeeName" ng-pattern="/^[0-9]{1,7}$/"/></custom-input>
<span ng-show="myForm['employee.name'].$error.required">This is a required field</span>
<span ng-show="myForm['employee.name'].$error.pattern">This is a invalid field</span>
</form>
</div>
<script type="text/ng-template" id="/templates/customInput.html">
<div>
<input type="text" name="{{name}}" ng-model="newInput" id="{{id}}">
</div>
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
</body>
</html>
与此对应的javascript是:
angular.module('validationApp', [])
.controller("ValidationController", function(){
})
.directive("customInput", function(){
return {
restrict: "E",
require : "ngModel",
replace: "true",
templateUrl : "/templates/customInput.html",
scope : {
id : "@", //bind id to scope
name : "@" //bind name to scope
},
link: function(scope, element, attrs, ngModelCtrl){
//When newInput is updated, update the model of original input
scope.$watch('newInput', function(newValue){
ngModelCtrl.$setViewValue(newValue);
});
//On first load, get the initial value of original input's model and assign it to new input's model
ngModelCtrl.$render = function(){
var viewValue = ngModelCtrl.$viewValue;
if(viewValue){
scope.newInput = viewValue;
}
}
}
}
});
我正在尝试在此自定义输入上应用ng-required
和ng-pattern
验证。我遇到了两个问题:
- 在 angularjs 1.2.6 中,我可以在 1.3.0 中触发
ng-required
验证,custom-input
但不会触发验证。 - 我无法
ng-pattern
在两个版本中触发验证。
我的理解是$setViewValue
将ngModelController
触发所有验证。上面是一个人为的例子,我的实际用例是创建一个自定义指令,为 SSN 呈现三个输入框。
以下分别是 1.2.6 和 1.3.0 的 plunker 链接: