我分叉的Plunker和做了一些改進,以使代碼的可讀性,特別是使編輯狀態更透明和隱藏編輯控制時不處於編輯模式。
的主要問題是:
- 不是管理編輯境界清楚。
- 不需要引用外部ng-repeat $ parent。$ index中的正確索引。
希望它有幫助。
Plunker Here下面的代碼:
視圖。HTML
<body ng-controller="demoController">
editing {{editing}}
<div ng-repeat="classified in classifieds">
<h1>{{classified.name }}</h1>
<ul>
<li ng-repeat="thought in classified.thoughts">
{{ thought }} <button ng-click="remove(classified, $index)">Remove</button><button ng-click="edit($parent.$index, $index)">Edit</button>
</li>
</ul>
<div ng-show="editing[$index].editing">
<input type="text" ng-model="editing[$index].thought">
<button type="submit" ng-click="save($index)">Save</button>
</div>
</div>
Controller.js
// Code goes here
var app = angular.module('app', []);
app.controller('demoController', function($scope) {
$scope.input = [];
$scope.editing = {};
$scope.classifieds = [
{
"name": "Wittgenstein",
"thoughts": ["thought 1", "thought 2", "thought 3"]
},
{
"name": "King",
"thoughts": ["thought 1", "thought 2", "thought 3"]
}
];
/* Add */
$scope.save = function(classifiedIndex) {
var editingMeta = $scope.editing[classifiedIndex];
var thoughtIndex = editingMeta.thoughtIndex;
$scope.classifieds[classifiedIndex].thoughts[thoughtIndex] = editingMeta.thought;
delete $scope.editing[classifiedIndex];
}
/* Remove*/
$scope.remove = function(classified, i) {
$scope.classified.thoughts.splice(i, 1);
}
/* Edit */
$scope.edit = function(classifiedIndex, thoughtIndex) {
var classified = $scope.classifieds[classifiedIndex];
$scope.editing[classifiedIndex] = {
editing: true,
thoughtIndex: thoughtIndex,
thought: classified.thoughts[thoughtIndex]
}
}
});