AngularJS: how to compile form in a directive

2019-08-29 08:20发布

I'm trying to create a custom directive that set 'required' and 'disabled' attributes to the element (form input). The directive gets this data from the scope object. But clearing of required field doesn't set my form to invalide state. I think it's about form compilation after changing the attribute. I tried to do that but got an infinite loop :( How to compile my form correctly?

Here is plunker

2条回答
ゆ 、 Hurt°
2楼-- · 2019-08-29 09:06

You could just use ng-disabled and ng-required, instead of adding the attributes in a directive.

<div>
  <label for="username">username2</label>
  <input ng-model="data.account.username2" 
  ng-disabled="paintData['data.account.username2'] == 'RO'" 
  ng-required="paintData['data.account.username2'] == 'R'" />
</div>

Alternatively, you could define a directive template that uses ng-disabled and ng-required, and replace the original element with it:

.directive('metaValidate', function($compile) {
  return {
    restrict: 'A',
    replace: true,
    scope: {
      model: '=',
      paint: '='
    },
    template: '<input ng-model="model" ng-disabled="readonly" ng-required="required"/>',
    link: function(scope, element, attrs) {
      scope.required = scope.paint[element.attr('model')] === 'R';
      scope.readonly = scope.paint[element.attr('model')] === 'RO';
    }
  };
});

Then, use it like this:

<input model="data.account.username2" meta-validate paint="paintData"/>

I prefer the first approach, because it can respond to changes to paintData. But, you have to repeat the property name several times.

If you want to try this code, here is an update of your Plunker.

查看更多
放荡不羁爱自由
3楼-- · 2019-08-29 09:12

Recompiling the element could work, but in order to avoid the infinite loop you need to first remove the meta-validate attribute (which would cause yet more compiling etc):

/* At the end of the directive's link function */
attrs.$set('metaValidate', undefined);
$compile(element)(scope);         

See, also, this short demo.

查看更多
登录 后发表回答