我正在尝试创建一个包含动态输入框的表单。我正在尝试使用ng-models来处理数组项目,我显然做错了。
我的问题似乎是在模板中索引范围数组lineItems。
这是我的jsfiddle:http://jsfiddle.net/dk253/9ykuuobq/
这是我的代码:
<div ng-controller="MyCtrl">
<h2>Testing Arrays</h2>
<button type="button" ng-click="addItem()" class="btn btn-primary">Howdy</button>
<div ng-repeat="item in items" item="item" my-index="{{$index}}" itemlist></div>
</div>
<script type="text/ng-template" id="template.html">
<div class = "row">
<div class = "col-xs-6"> <input name= "itemNum-{{item.itemNum}}" type = "number" class="form-control"
placeholder = "Item Number" ng-model="items[{{item.itemNum}}].itemNum" required> </div>
<div class = "col-xs-6"> <input name= "name-{{item.itemNum}}" type = "text" class="form-control"
placeholder = "Name" ng-model="items[{{item.itemNum}}].name" required> </div>
</div>
</script>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.count = 0;
$scope.items = [];
var baseItem = {
itemNum: 0,
name: "New"
};
$scope.addItem = function () {
newItem.itemNum = $scope.count;
var newItem = angular.copy(baseItem);
newItem.itemNum = $scope.count;
$scope.items.push(newItem);
$scope.count += 1;
};
});
myApp.directive('itemlist', function ($compile) {
return {
templateUrl: 'template.html',
restrict: 'A',
replace: true,
transclude: true,
scope: { item: '=', myIndex: '@' }
};
});
感谢您的帮助!
答案 0 :(得分:1)
小提琴有几个错误:
$scope.addItem
在定义之前使用newItem
。删除第一行(可能是拼写错误)。ng-model
:
{{...}}
的表达式。因此ng-model="items[{{item.itemNum}}].itemNum"
将成为ng-model="items[item.itemNum].itemNum"
items
变量不可见。但item
可见,因此您只需:ng-model="item.itemNum"
(和ng-model="item.name"
)。通过这些更改,它似乎正在运行:http://jsfiddle.net/9ykuuobq/19/