在AngularJS中使用带有输入的动态大小的行集

时间:2014-03-17 13:53:56

标签: javascript angularjs angularjs-ng-repeat

我的数据模型类似于以下

records
└─ record
   └─ id: 0
   └─ name: "Foo"
   └─ property: true
└─ record
   └─ id: 1
   └─ name: "Bar"
   └─ property: false
└─ record
   └─ id: 2
   └─ name: "Baz"
   └─ property: true

我想使用以下内容创建用户界面:

<div class="row">
  <input type="hidden" value="0"></input>
  <input type="text" value="Foo"></input>
  <input type="checkbox" checked></input>
  <button>Remove</button>
</div>
...

我正在为我的项目使用angular,而我的代码片段是

<div ng-controller="ThingsController">
  <div class="row" ng-repeat="thing in things" ng-controller="ThingController">
    <input type="hidden" ng-model="id"></input>
    <input type="text" ng-model="name"></input>
    <input type="checkbox" ng-model="property"></input>
    <button ng-click="remove()">Remove</button>
  </div>
 </div>

使用以下控制器:

angular.module('mymodule', [])
.controller('ThingsController', function($scope) {

  $scope.things = [{
    id: 0,
    name: "Foo"
    property: true
  }, {
    id: 1,
    name: "Bar"
    property: false
  }, {
    id: 2,
    name: "Baz"
    property: true
  }];

  $scope.remove = function(idx) {
    $scope.things.splice(idx, 1);
  };

  $scope.add = function() {
    $scope.things.push({
      id: $scope.things.length,
      name: 'Placeholder',
      property: true
    });
  };
})

.controller('ThingController', function($scope) {

  $scope.remove = function() {
    $scope.$parent.remove($scope.$index);
  };
});

此代码不起作用 - 当我们推送到ng-repeat时会创建一组新的输入字段,但模型未正确连接。当我检查情况时,我发现实际上有两个范围,一个用于ng-repeat,另一个用于ng-controller

我的问题是:我做错了什么?我是否需要不使用新的控制器?有没有人使用这种模式来创建可变长度的表单?

1 个答案:

答案 0 :(得分:1)

访问ng-repeat内的对象时,您必须使用thing.idthink.namethink.property等内容。

<div ng-controller="ThingsController">
  <div class="row" ng-repeat="thing in things">
    <input type="hidden" ng-model="thing.id"></input>
    <input type="text" ng-model="thing.name"></input>
    <input type="checkbox" ng-model="thing.property"></input>
    <button ng-click="remove($index)">Remove</button>
  </div>
 </div>

并将您的remove函数放入ThingsController

$scope.remove = function(index) {
    $scope.things.splice(index, 1);
};

你真的不需要ThingController