【发布时间】:2014-12-13 20:55:29
【问题描述】:
我希望创建一个自定义指令,它呈现为输入类型元素。该指令应该重用 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 中,我可以在
custom-input中触发ng-required验证,但在 1.3.0 中,验证不会被触发。 - 我无法在两个版本中触发
ng-pattern验证。
我的理解是ngModelController 中的$setViewValue 将触发所有验证。上面是一个人为的例子,我的实际用例是创建一个自定义指令,为 SSN 呈现三个输入框。
以下分别是 1.2.6 和 1.3.0 的 plunker 链接:
【问题讨论】:
-
replace: true 参数现在已被弃用。避免使用它。
-
使用 ng-form。表单不适用于嵌套表单。
-
我没听懂你。我在这里看不到任何嵌套表单!
标签: angularjs angularjs-directive angularjs-validation