Sunday, 15 July 2012

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



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

i have big form many input elements, , if form beingness used render element read only, add together ng-readonly directive input elements in form. go through , set ng-readonly 1 each input element, isn't dry , hard maintain.

i have thought of few possibilities:

a directive on form tag looks @ children , adds ng-readonly directive override input directive add together ng-readonly directive in scope.readonly true.

the problem i'm not sure how either of these work (pretty new angular). know have utilize $compile or $apply in someway angular pick newly added directive, i'm not sure how go it.

first alternative looks in 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/

angularjs

No comments:

Post a Comment