最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Binding using ng-model inside ng-repeat in angularjs - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked May 9, 2013 at 17:20 shahalpkshahalpk 3,4627 gold badges39 silver badges56 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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>
发布评论

评论列表(0)

  1. 暂无评论