将对象数组绑定到$ scope

时间:2017-01-12 10:54:08

标签: html angularjs html5 angularjs-directive mean-stack

<div data-ng-repeat="div in divs">
    <label>First Name</label>
    <input type="text" name="fname" ng-model="user.fname[$index]">
    <label>Second Name</label>
    <input type="text" name="sname" ng-model="user.sname[$index]">
</div>
<button ng-click="addDivs()">Add More Person</button>


angular.module('user', []).controller('UserCtrl', function($scope){
    $scope.divs = [1];
    $scope.addDivs = function(){
        $scope.divs.push({});
    }
}

当我们有2个div 所需的数据格式是:

  

[{fname:&#39; name1&#39;,sname:&#39; name2&#39; },{fname:&#39; name3&#39;,   SNAME:&#39; NAME4&#39; }]

但输出结果如下:

  

{fname:[&#39; name1&#39;,&#39; name3&#39; ],sname:[&#39; name2&#39;,&#39; name]}

如何建模html以获得所需格式的数据?

1 个答案:

答案 0 :(得分:1)

这是你期待的吗?

&#13;
&#13;
angular.module('user', []).controller('UserCtrl', function($scope){
  $scope.persons = [];  
  $scope.addDivs = function(){
        $scope.persons.push({fname: $scope.user.fname, sname: $scope.user.sname});
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="user" ng-controller="UserCtrl">
<div>
    <label>First Name</label>
    <input type="text" name="fname" ng-model="user.fname">
    <label>Second Name</label>
    <input type="text" name="sname" ng-model="user.sname">
</div>
  <div data-ng-repeat="person in persons"> {{person.fname}}  {{person.sname}}</div>
<button ng-click="addDivs()">Add More Person</button>

</div>
&#13;
&#13;
&#13;