AngularJS:如何编译形式指令 [英] AngularJS: how to compile form in a directive

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

问题描述

我试图创建一个集必要和禁用属性的元素(表单输入)的自定义指令。该指令会从范围对象该数据。但是,需要现场的清理不设置我的形式invalide状态。我认为这是对的形式编译改变属性之后。我想这样做,但有一个无限循环:(
如何正确编译我的形式?

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?

下面是 plunker

推荐答案

您可以只使用 NG-停用 NG-要求,而不是在指令中添加的属性。

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>

另外,你可以定义使用 NG-停用 NG-要求指令模板,更换原始元素与它:

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

我preFER第一种方法,因为它可以给变为 paintData 回应。但是,你不得不重复属性名几次。

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

如果你想尝试这个code,是更新您的Plunker

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

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

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