Угловая директива с динамически генерируемыми полями ввода, которые не могут отображать проверку

После 3 дней изучения stackoverflow и других сайтов я вернулся к исходной точке.

Моя задача: мне нужно проверить динамически генерируемые поля формы.

HTML:

 <form name="myForm">
    <form-field content="field" model="output[field.uniqueId]" ng-repeat="field in formFields"></form-field>
 </form>

Контроллер:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
$scope.formFields = [
    {
    "fieldName": "Your Name",
    "uniqueId": "your_name_0",
    "fieldType": "text",
    "isMandatory": true
    },
    {
    "fieldName": "Description",
    "uniqueId": "description_1",
    "fieldType": "textarea",
    "isMandatory": true,
    }
];

$scope.output={};
}

Директива:

myApp.directive("formField",function($compile){
var templates = {
    textTemplate:'<div class="form-group"><label for="{{content.uniqueId}}" >{{content.fieldName}}</label> <span ng-show="content.isMandatory" class="sub_reqText">*</span><span ng-show="form.content.fieldName.$invalid">Please check this field.</span><input type="text" ng-model="model" name="{{content.uniqueId}}" class="form-control" ng-required="content.isMandatory" id="{{content.uniqueId}}"/> </div><br>',
    textareaTemplate:'<div class="form-group"><label for="{{content.uniqueId}}" >{{content.fieldName}}</label> <span ng-show="content.isMandatory" class="sub_reqText">*</span> <span ng-show="form.content.fieldName.$invalid">Please check this field.</span> <textarea ng-model="model" name="{{content.uniqueId}}" id="{{content.uniqueId}}"  class="form-control" ng-required="content.isMandatory"></textarea> </div>' 
};

var getTemplate = function(content, attrs){
    var template = {};
    template = templates[content.fieldType+"Template"];
    if(typeof template != 'undefined' && template != null) {
            return template;
        }
        else {
            return '';
        }
};


var linker = function(scope, element, attrs){        
    element.html(getTemplate(scope.content, attrs)).show();        
    $compile(element.contents())(scope);
}

return {
    restrict:"E",        
    replace:true,        
    link:linker,
    scope:{
        content:'=',
        model:'=?'
    }
};
});

Очевидно, существует некоторая проблема с областью действия, потому что я не могу получить доступ к полям формы за пределами директивы и не могу получить доступ к имени формы внутри директивы. Я также знаю, что свойство $scope.myForm.name не может быть угловым выражением привязки, но я не уверен, как его переписать, чтобы оно работало.

Это jsfiddle: http://jsfiddle.net/scheedalla/57tt04ch/

Любое руководство будет очень полезно, спасибо!


person user3495469    schedule 23.01.2015    source источник
comment
создаются две области: одна из-за ng-repeat, а другая из-за изолированной области   -  person Pankaj Parkar    schedule 24.01.2015
comment
Узнал много концепций, решая эту проблему. Кстати, это был хороший вопрос .. Спасибо.   -  person Pankaj Parkar    schedule 26.01.2015


Ответы (1)


При отладке проблемы я обнаружил, что атрибут имени неправильно скомпилирован для формы. Он показывал {{content.uniqueId}} в названии, но на самом деле он правильно отображался в пользовательском интерфейсе.

Например. Для ниже html.

<input type="text" ng-model="model" name="{{content.uniqueId}}" class="form-control" 
ng-required="content.isMandatory" id="{{content.uniqueId}}"/>

имя отображается как name="your_name_0", но в коллекции форм отображается {{content.uniqueId}} с директивой интерполяции.

Похоже, имя не интерполировано должным образом.

Затем обнаружил проблему с AngularJS: "Вы не можете динамически устанавливать атрибут имени для Проверка формы».

Примечание. Вышеупомянутая проблема была исправлена ​​в Angular 1.3 (атрибуты имен правильно интерполируются).

& Если вы хотите работать с ними внутри ng-repeat, вам всегда следует использовать вложенные ng-form. Члены внутри ng-repeat будут иметь свою собственную форму, и с помощью этой внутренней формы вы сможете обрабатывать свою проверку. Ссылка для справки

ИЗМЕНЕНИЕ КОДА

var templates = {
        textTemplate: '<ng-form name="form">'+
    '<div class="form-group">'+
        '<label for="{{content.uniqueId}}">{{content.fieldName}}</label> '+
          '<span ng-show="content.isMandatory" class="sub_reqText">*</span>'+
          '<span ng-show="form.input.$invalid">'+
          'Please check this field.'+
          '</span>'+
        '<input type="text" ng-model="model1" name="input" class="form-control" ng-required="content.isMandatory" id="{{content.uniqueId}}" /> '+
    '</div>'+
'</ng-form>'+
'<br>',
        textareaTemplate: '<ng-form name="form">'+
    '<div class="form-group">'+
        '<label for="{{content.uniqueId}}">{{content.fieldName}}</label>'+
          '<span ng-show="content.isMandatory" class="sub_reqText">*</span> '+
          '<span ng-show="form.textarea.$invalid">Please check this field.</span>'+
          '<textarea ng-model="model" name="textarea" id="{{content.uniqueId}}" class="form-control" ng-required="content.isMandatory"></textarea>'+
    '</div>'+
'</ng-form>'
    };

Только я изменил html шаблона, в основном добавил <ng-form></ng-form> для шаблонов и обработал проверку на основе этого во внутренней форме.

Вот ваша рабочая скрипта

Надеюсь, это прояснило ваше понимание. Спасибо.

person Pankaj Parkar    schedule 26.01.2015
comment
Великолепно! Это именно то, что я искал. Большое спасибо! Рад, что ты тоже многому научился :) - person user3495469; 26.01.2015
comment
@ user3495469 Рад помочь вам .. На самом деле это был хороший вопрос. Сделал много исследований и разработок, чтобы найти решение для вас :) - person Pankaj Parkar; 26.01.2015