2

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.

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

This is great, thanks. I didn't realize that the elem object is a jQuery object, really makes traversing the DOM much more familiar.
But note that if you don't include jQuery into your project, elem is a jQlite object which provides only selected methods from jQuery (docs.angularjs.org/api/ng/function/angular.element)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.