如何在AngularJS中向输入元素动态添加指令 [英] How to dynamically add a directive to an input element in AngularJS

查看:43
本文介绍了如何在AngularJS中向输入元素动态添加指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多输入元素的大型表单,并且如果此表单用于呈现只读元素,我想向该表单中的所有输入元素添加ng-readOnly指令.我可以遍历每个输入元素ng-readOnly,但这不是很干燥,并且很难维护.

I have a large form with many input elements, and if this form is being used to render an element that is read only, I would like to add the ng-readOnly directive to all input elements in the form. I could go through and put ng-readOnly one each input element, but that isn't very dry and it would be difficult to maintain.

我想到了几种可能性:

  1. form标记上的指令,该指令可查看所有子项并添加ng-readOnly指令
  2. 重写输入指令,将ng-readOnly指令添加到scope.readOnly为true.

问题是我不确定这两种方法如何工作(对于Angular来说还很新).我确实知道我必须以某种方式利用$ compile或$ apply来获取新加入的指令的角度,但我不确定该怎么做.

The problem is I'm not sure how either of these would work (pretty new to Angular). I do know I would have to utilize $compile or $apply in someway to get angular to pick up the newly added directive, I'm just not sure how to go about it.

推荐答案

我认为第一个选项看起来不错:

First option looks good in my opinion:

<div ng-app="app" ng-controller="ctrl">
    <form transform-inputs>
    <input type="text" ng-model="model1"/>
    <input type="text" ng-model="model2"/>
    <input type="text" ng-model="model3"/>
    </form>
</div>

指令:

.directive('transformInputs',function($compile){
    return{
        restrict: 'AE',
        link: function(scope, elem, attrs){
            elem.children('input').attr('ng-read-only',true);
            $compile(elem.contents())(scope);
        }
    }
})

http://jsfiddle.net/aartek/7RHW7/

这篇关于如何在AngularJS中向输入元素动态添加指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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