0

I'm trying to get forms with fields created from config, with validation and other fine goods.

Here: http://plnkr.co/edit/8cP5YMKUGu6LfBCsRxAZ?p=preview is a solution, which works, but when I try to go step more - to add logic e.g (if attrs.hasOwnProperty('required') then add something to template) - i'm stucked. (to be exact - in this plunker i'd like to remove all staff connected to remove and add it only in case if field-required is true.

So I THINK (but may be wrong) that I have to use some link or compile function which prepares the template for each field.

So I produce sth like this:

  KPNDirectives.directive("formField", function () {
  return {
    restrict: 'E',
    replace:true,
    scope: {
      fieldModel : '=ngModel'
    },
    link: function (scope, element, attrs) {
      var type = attrs.fieldType || 'text'
      var htmlText = 
       '<div class="form-group" ng-form="form" ng-class="{true: \'has-error\', false: \'has-success\'}[form.'+attrs.fieldName+'.$invalid]">'+
  '<label class="control-label col-sm-2" for="'+attrs.fieldName+'">'+attrs.fieldLabel+'</label>'+
  '<div class="col-sm-6">'+
    '<input class="form-control" type="'+type+'" placeholder="enter valid name" name="'+attrs.fieldName+'" ng-model="'+scope.fieldModel+'" ng-minlength=3 ng-maxlength=20 required/>'+
    '<span class="help-block">'+
      '<span ng-show="form.'+attrs.fieldName+'.$error.required">Required field</span>'+
      '<span ng-show="form.'+attrs.fieldName+'.$error.minlength">Too few chars - min is (6)</span>'+
      '<span ng-show="form.'+attrs.fieldName+'.$error.maxlength">Too much chars - max is (20)</span>'+
      '&nbsp;'+
    '</span>'+
  '</div>'+
'</div>';
      element.replaceWith(htmlText);
    }
  }
  });

But it doesn't work.

Here's plunker http://plnkr.co/edit/OZMuxzsnoVmATpeTdSW9?p=preview

Tomasz Brzezina
  • 1,452
  • 5
  • 21
  • 44
  • I think you'll find your answer [here](http://stackoverflow.com/questions/19224028/add-directives-from-directive-in-angularjs). I'm not quite sure where you want to put this logic but my bet is that you're looking for a way to compile the directives in your template against your current scope. You can either use the $compile service or see the given link for a two stage compile and link. – Lawrence Jones Dec 28 '13 at 12:19

1 Answers1

1

Try this DEMO

There are some problems with your code

  • You have to define template for your directive: template:"<div></div>" and append html to it: element.append(htmlText);
  • Use fieldModel : '=' instead of fieldModel : '=ngModel' because you use field-model="field.model" in your html.
  • Use ng-model="fieldModel" instead of ng-model="'+scope.fieldModel+'"
  • You need to compile your html using $compile service: $compile(element.contents())(scope);
Khanh TO
  • 48,509
  • 13
  • 99
  • 115