I would like to create a form with the fields created in the directive. Data binding works correctly, but validation does not work.
this is 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>
controller and field directive:
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); } } });
the problem is that validation for the name field does not work, and the required verification text is never displayed. Maybe the form in ng-show unknown in the directive. But I do not know how to pass the form to a field directive. Can you help me how to fix this? Thanks.
there is real-time code here: http://plnkr.co/edit/j0xc7iV1Sqid2VK6rMDF?p=preview
angularjs angularjs-scope angularjs-directive
Marekli
source share