Binding using ng model inside ng-repeat in angularjs

I am trying to bind the User model to a list of input fields. I do not know the fields in advance, so I have to write general code to customize 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 am trying to iterate over the fields and show the input field for each field (available in the area). But the binding is incorrect, as I try to evaluate the expression inside the ng model.

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

Here fiddle

Any help?

+4
source share
1 answer

Your problem will be resolved below.

 <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> 
+6
source

Source: https://habr.com/ru/post/1479962/


All Articles