AngularJS: how to compile form in a directive

主宰稳场 提交于 2019-12-25 02:52:57

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23746574/angularjs-how-to-compile-form-in-a-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!