1

I'we read some posts about using ng-switch or directive when changing and input type. I now have this code but it is very repetitive.

<input ng-change="change();" ng-if="! item.data && item.mapping == 'password'" 
type="password" class="login-input" id="{{item.mapping}}" 
ng-model="item.content" placeholder="{{item.name | mandatory:this.item.minLength }}"
ng-minlength="{{item.minLength}}"> 

<input ng-change="change();" ng-if="! item.data &&  item.mapping != 'password'"
type="text" class="login-input" id="{{item.mapping}}" ng-model="item.content"
placeholder="{{item.name | mandatory:this.item.minLength }}"
ng-minlength="{{item.minLength}}"> 

I only want to change the type. How can I make this less DRY with angular? How to use directives when changing the type?

1 Answer 1

1

If your attributes on input are similar then you can create a template out of this input field

<script id="others" type="ng/template">
    <input ng-change="change();" class="login-input" id="{{item.mapping}}" ng-model="item.content"
      placeholder="{{item.name | mandatory:this.item.minLength }}"
      ng-minlength="{{item.minLength}}"> 
</script>


<script id="password" type="ng/template">
    <input ng-change="change();" class="login-input" id="{{item.mapping}}" ng-model="item.content"
      placeholder="{{item.name | mandatory:this.item.minLength }}"
      ng-minlength="{{item.minLength}}"> 
</script>

and then use ng-include to add the input control to where ever you want

<ng-include src="item.mapping == 'password'?item.mapping:'others'"></ng-include>

You can pass data to the template to keep it reusable using ng-init.

Also remember ng-include creates a new scope.

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

4 Comments

Is there some way of doing this without changing scope?
It does not change scope, but creates a child scope. Which means you can access parent scope. Look at this wiki to understand the implications github.com/angular/angular.js/wiki/Understanding-Scopes. Else you have to wrap this content into directive.
Can you give me a push on how to create such direction?
Isn't this ng/template very repetitive? I want to be able to have the same data and just switch the type. Must be alot of folks building dynamic forms but it doesn't seem to be a good solution to this.

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.