你可以在这里看到我有一个非常好用的添加/删除/编辑功能,用于从数组中删除对象。
我正在努力的是
编辑内联并将更改推回到数组中。
向DOM添加新输入字段以将新对象推送到数组中。
app = angular.module("sparta", []);
window.CompetitionController = function($scope) {
$scope.activities = [{
id: 6431,
name: "Meeting",
points: 20
}, {
id: 6432,
name: "Deal",
points: 100
}];
$scope.addNewActivity = function() {
//This function should create 2 new input fields
//The user should input the name and points
//We can ignore the id for now
//Then the object should be craeted and pushed in as you see below with the mock data.
var updatedActivities = {
id: 6433,
name: "Call",
points: 5
};
$scope.activities.push(updatedActivities);
}
$scope.editActivity = function(activity) {
var selectedActivity = activity;
console.log(selectedActivity);
}
$scope.removeActivity = function(activity) {
activityId = activity.id; //the activity id
var i = 0;
for (var item in $scope.activities) {
if ($scope.activities[item].id == activityId)
break;
i++;
}
$scope.activities.splice(i, 1);
}
}
HTML如下:
<body ng-app="sparta">
<div class="container" ng-controller="CompetitionController">
<div ng-repeat="activity in activities">
{{activity.name}} - {{activity.points}}
<button ng-click="editActivity(activity)">Edit</button>
<button ng-click="removeActivity(activity)">Remove</button>
</div>
<div class="addNew">
<button ng-click="addNewActivity()">Add New</button>
</div>
</div>
</body>
我试图在小提琴中尽可能多地给予 - 我喜欢的是对addNewActivity()函数和editActivity()函数的一些指导以及如何内联编辑两个输入字段并保存更改进入阵列。
提前致谢!
答案 0 :(得分:1)
您可以从以下位置更改html:
{{activity.name}} - {{activity.points}}
要:
<input type="text" ng-model="activity.name"/> - <input type="text" ng-model="activity.points"/>
所以你得到了双向绑定。
答案 1 :(得分:1)
这是另一个简单的例子:http://jsfiddle.net/A5xZ9/2/
基本上你隐藏输入字段,直到点击活动编辑按钮,在这种情况下你显示输入字段并隐藏文字:
<div ng-show="activity.isEdited">
<input type="text" ng-model="activity.name"/> - <input type="text" ng-model="activity.points"/>
<button ng-click="activity.isEdited = false">Ok</button>
</div>
<div ng-hide="activity.isEdited">
{{activity.name}} - {{activity.points}}
<button ng-click="activity.isEdited = true">Edit</button>
<button ng-click="removeActivity(activity)">Remove</button>
</div>
可以进行很多改进,例如编辑活动的本地副本并仅在用户按下确定时更新原始属性,并提供取消按钮。