这是我的脚本文件..
app.controller('userController', function PostController($scope, userFactory) {
$scope.users = [];
$scope.user = { items : [] , attributes : [] };
$scope.editMode = false;
$scope.addItem = function (index) {
$scope.user.items.push({
Name: $scope.newItemName,
Value: $scope.newItemValue
});
};
$scope.deleteItem = function (index) {
$scope.user.items.splice(index, 1);
};
}
这是我的HTML文件
<div class="modal-body">
<form class="form-horizontal" role="form" name="adduserform">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" data-ng-model="user.Name" class="form-control" id="title" placeholder="Your Name" required title="Enter your name" />
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Address</label>
<div class="col-sm-10">
<input type="text" data-ng-model="user.Address" class="form-control" id="title" placeholder="Your Address" required title="Enter your address" />
</div>
</div>
<div class="form-group">
<label for="title" class="col-sm-2 control-label">ContactNo</label>
<div class="col-sm-10">
<input type="text" data-ng-model="user.ContactNo" class="form-control" id="title" placeholder="Your ContactNo" required title="Enter your contactno" />
</div>
</div>
<div class="form-group">
<ul class="nav" class="col-sm-2" >
<label for="title" class="col-sm-2 control-label">Variations</label>
<div class="col-sm-10">
<input type="text" value="ItemName" class="form-control" id="title" ng-model="newItemName" required placeholder="Name of new item...">
<input type="text" value="ItemName" class="form-control" id="title" ng-model="newItemValue" required placeholder="Value of new item...">
</div>
<div class="col-sm-offset-3">
<button ng-click="addItem()" class="btn btn-primary" >Add Me</button>
<table class="table table-hover">
<tr data-ng-repeat="item in user.items">
<td>
<p>{{item.Name}}</p>
</td>
<td>
<p>{{item.Value}}</p>
</td>
<td>
<a ng-click="deleteItem($index)" class="delete-Item">x</a>
</td>
</tr>
</table>
</div>
</ul>
</div>
我怀疑的是,每当我点击addItem时,它将被存储为Name:“xxx”,Value:“yyy”,但我希望它存储为xxx:yyy。有没有办法做到这一点。我是角度js的新手。请帮我。谢谢
答案 0 :(得分:1)
尝试在addItem
方法中使用此代码:
$scope.addItem = function (index) {
var newItem = {};
newItem[$scope.newItemName] = $scope.newItemValue;
$scope.user.items.push(newItem);
};
在此代码中,您首先为新项目创建一个对象,然后从newItemName
创建该属性,并为其指定一个来自字段newItemValue
的值。然后你把它推到一个数组。
这种方法的一个问题是像<p>{{item.Name}}</p>
这样的绑定不起作用,因为没有名为Name
的属性了。我不知道你为什么要以你描述的格式存储数据,但是为了使旧的绑定工作,你也可以使用旧的属性:
$scope.addItem = function (index) {
var newItem = {Name: $scope.newItemName, Value: $scope.newItemValue };
newItem[$scope.newItemName] = $scope.newItemValue;
$scope.user.items.push(newItem);
};
答案 1 :(得分:0)
使用地图代替项目列表:
$scope.user = { items : {} , attributes : [] };
$scope.user.items[$scope.newItemName] = $scope.newItemValue;