Zachary Wright
Zachary Wright

Reputation: 24070

How to dynamically add a directive to an input element in AngularJS

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.

I have thought of a few possibilities:

  1. A directive on the form tag that looks at all the children and adds the ng-readOnly directive
  2. Override the input directive to add the ng-readOnly directive in scope.readOnly is true.

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.

Upvotes: 2

Views: 2817

Answers (1)

akn
akn

Reputation: 3722

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:

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

Upvotes: 2

Related Questions