我正在尝试用angularjs编写编辑功能。 它几乎做到了。但是该值不会在视图部分中更新。 谁能帮忙?我的代码如下我正在使用 ng-repeat="书中书">
目录
<li ng-click="delegate.editPost()">Edit</li>
<div ng-show="showEditPost">
<div ng-click="delegate.savePost()">Save</div>
<p ng-if="showEditPost==false">{{book.text}}</p>
<div ng-if="showEditPost == true">
<textarea >{{edit.text}}</textarea>
</div>
</div>
控制器
editPost:function(){
$scope.showEditPost=true;
$scope.edit=angular.copy($scope.books);
},
save:function(){
var Obj = {
text: $scope.edit.text
}
editService.edit( Obj,this.onSuccess, this.onFailure);
},
onSuccess:function(){
$scope.showEditPost=false;
angular.copy($scope.edit,$scope.books);
}
我认为你把它弄得太复杂了。但是,与其使用整个数组,不如传递索引并使用单个元素。这是一个简单的演示:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.books = [{
"text": "Book 1"
}, {
"text": "Book 2"
}];
$scope.showEditPost = $scope.books.map(function(_) {
return false;
}); // populating array with `false` values
$scope.editPost = function(index) {
$scope.showEditPost[index] = true;
// edit is now an element and not an entire array
$scope.edit = angular.copy($scope.books[index]);
}
$scope.savePost = function(edit, index) {
$scope.books[index] = edit;
$scope.showEditPost[index] = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<!--
`track by $index` is added to allow repetition/duplicates
-->
<div ng-repeat="book in books track by $index">
<!-- passing index with `$index` -->
<button ng-click="editPost($index)">Edit</button>
<!-- editing only an individual box by using index -->
<p ng-if="!showEditPost[$index]">{{book.text}}</p>
<div ng-if="showEditPost[$index]">
<button ng-click="savePost(edit,$index)">Save</button><br>
<!-- `ng-model` is added to allow modification -->
<textarea ng-model="edit.text">{{edit.text}}</textarea>
</div>
</div>
</div>