我想用指令创建的字段创建表单.数据的数据绑定正常工作但验证不起作用.
这是html:
<body ng-controller="MainCtrl"> <h1>form</h1> <form name="form"> <div ng-repeat="conf in config"> <div field data="data" conf="conf"></div> </div> </form> <pre>{{data|json}}</pre> </body>
控制器和字段指令:
var app = angular.module('plunker',[]); app.controller('MainCtrl',function($scope) { $scope.data = {name: '',age: ''} $scope.config = [ {field: 'name',required:true},{field: 'age'} ]; }); app.directive('field',function ($compile) { return { scope: { data: '=',conf: '=' },link: function linkFn(scope,element,attrs) { // field container var row = angular.element('<div></div>'); // label row.append(scope.conf.field + ': '); // field input var field = angular.element('<input type="text" />'); field.attr('name',scope.conf.field); field.attr('ng-model','data.' + scope.conf.field); if (scope.conf.required) { field.attr('required','required'); } row.append(field); // validation if (scope.conf.required) { var required = angular.element('<span>required</span>'); required.attr('ng-show','form.' + scope.conf.field + '.$error.required'); row.append(required); } $compile(row)(scope); element.append(row); } } });
问题是字段名称的验证不起作用,并且永远不会显示所需的验证文本.可能是ng-show中的表格在指令中是未知的.但我不知道如何将表单传递给字段指令.你能帮我解决一下吗?谢谢.
去做:
原文链接:https://www.f2er.com/angularjs/141855.html之前:
$compile(row)(scope); element.append(row);
后:
element.append(row); $compile(row)(scope);
‘planker’中的p / s为设施添加css:
.ng-invalid { border: 1px solid red; }