12

In some cases I need to apply different attributes to a node based on properties in my model.

For example, in one case I need to add a 'required' tag and in another case not. I've been using ng-if with different branches to accomplish this but the cases are getting out of hand quickly.

 <div ng-if="model.required">
    <input class="form-control"
           type="text"
           required 
           ng-model="model" />
 </div>
 <div ng-if="!model.required">

    // as different options arise,
    // i have more forks for each attribute combo

    <input class="form-control"
           type="text"
           ng-model="model" />
 </div>

Is there a better way to dynamic apply attributes to nodes?

2 Answers 2

13

I have quickly created a directive that allows you specify attributes dynamically.

http://jsfiddle.net/HB7LU/1806/

I'm not sure if it will have the desired effect you are after in this simple form, but it might be a good starting point. You essentially use:

<div dyn-attrs="someModelArray"></div>

And set your model accordingly:

$scope.someModelArray = [
    { attr: 'myattribute', value: '' },
    { attr: 'anotherattribute', value: 'val' }
];
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe merging this w/ the same approach the ng-css has would complete my case. Thanks!
Unfortunately, the attributes used in this approach cannot be directives. Well they can, but they won't be compiled by angular.
Note: Here it says: dyn-attrs, and in Fiddle, dyn-attr
6

In this case it would be best to make use of ngRequired:

<input class="form-control" type="text" ng-required="model.required" />

Comments

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.