4

I'm trying to bind a model 'User' to a list of input fields. I do not know the fields beforehand, so i've to write a generic code to setup the form based on the fields.

<script>
    function MyController($scope){
        $scope.fields  = ['name','password','dob'];
        $scope.user1 = {name:"Shahal",password:"secret"}
    };
</script>
<div ng-app ng-controller="MyController">
    <ul>
        <li ng-repeat="field in fields">
            <label>{{field}}</label><input type="text" ng-model="user1.{{field}}">
        </li>
    </ul>
    <pre>{{fields}}</pre>
</div>

I'm trying to loop through the fields and show a input field for each fields (available in scope). But the binding is not proper as i'm trying to evaluate an expression inside ng-model.

Basically i'm trying to show 3 input fields (name,password,dob) with the object user1 attached to the corresponding field.

Here's the fiddle

Any help?

1 Answer 1

6

Below will solve your problem

<script>
    function MyController($scope){
        $scope.fields  = ['name','password','dob'];
        $scope.user1 = {name:"Shahal",password:"secret"}
    };
</script>
<div ng-app ng-controller="MyController">
    <ul>
        <li ng-repeat="field in fields">
            <label>{{field}}</label><input type="text" ng-model="user1[field]">
        </li>
    </ul>
    <pre>{{fields}}</pre>
</div>
Sign up to request clarification or add additional context in comments.

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.