AngularJS:如何在指令中编译表单 [英] AngularJS: how to compile form in a directive

查看:34
本文介绍了AngularJS:如何在指令中编译表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义指令,为元素(表单输入)设置必需"和禁用"属性.该指令从范围对象中获取此数据.但是清除必填字段不会将我的表单设置为无效状态.我认为这是更改属性后的表单编译.我试图这样做,但得到了一个无限循环:(如何正确编译我的表单?

这里是 plunker

解决方案

你可以只使用 ng-disabledng-required,而不是在一个指令.

<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'"/>

或者,您可以定义一个使用 ng-disabledng-required 的指令模板,并用它替换原始元素:

.directive('metaValidate', function($compile) {返回 {限制:'A',替换:真的,范围: {型号:'=',油漆:'='},模板:'<input ng-model="model" ng-disabled="readonly" ng-required="required"/>',链接:函数(范围,元素,属性){scope.required = scope.paint[element.attr('model')] === 'R';scope.readonly = scope.paint[element.attr('model')] === 'RO';}};});

然后,像这样使用它:

我更喜欢第一种方法,因为它可以响应对 paintData 的更改.但是,您必须多次重复属性名称.

如果您想尝试此代码,这里是您的 Plunker 的更新.

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

解决方案

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.

这篇关于AngularJS:如何在指令中编译表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆