我有一个表,其行使用ng-repeat创建,具体取决于有多少帖子。点击I PUT将发布新状态发送到服务器,服务器发回更新的post对象。这很好用。
我的问题是,当ng-repeat包括|时orderBy:' - create_at'如下所示我无法在返回时使用新对象更新正确的帖子。传递给函数的索引以某种方式不同。当我删除过滤器时,它按预期工作
请注意,此代码中的%% %%是ng-bind而非{{}}
HTML 的
<div ng-controller="BlogCtrl" ng-init="getPosts()">
<table class="col-xs-12 table table-striped table-bordered table-hover">
<tr>
<th scope="col" class=""><h4>Created</h4></th>
<th scope="col" class=""><h4>Title</h4></th>
<th scope="col" class=""><h4>Status</h4></th>
</tr>
<tr ng-repeat="post in posts | orderBy: '-created_at'">
<th>%% post.created_at | date:'short'%%</th>
<th>
<span
popover="post.summary"
popover-trigger="mouseenter"
Popover-animation="true"
popover-placement="top">
%% post.title %%
</span>
</th>
<th>%% post.status %%
<a href="" ng-click="toggleStatus(post.id, post.status, $index)">
<span ng-if="post.status === 'DRAFT'">Approve</span>
<span ng-if="post.status !== 'DRAFT'">Set To Draft</span>
</a>
</th>
<th>View</th>
</tr>
</table>
</div>
app.js
myApp.controller('BlogCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.getUsersPosts = function () {
$http.get('/blog/userindex/' + $scope.userid).success(function (data, status) {
$scope.posts = data[0].posts;
});
};
$scope.toJsDate = function(str){
if(!str)return null;
var t = str.split(/[- :]/);
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
return d;
};
$scope.post = {};
$scope.addPost = function (userid) {
var post = $scope.post;
post.userid = userid;
$http.post('/blog/create', post).success(function(data, status) {
$scope.posts.push(data.newpost);
});
};
$scope.getPosts = function () {
$scope.posts = {};
$http.get('/posts').success(function (data, status) {
$scope.posts = data;
});
};
$scope.toggleStatus = function (postid, status, idx) {
var input = {};
console.log(postid);
console.log(status);
console.log(post);
if (status === 'DRAFT') {
input.status = 'APPROVED';
}
if (status === 'APPROVED') {
input.status = 'DRAFT';
}
$http.put('/posts/' + postid, input).success(function (data, status) {
$scope.posts[idx] = data;
});
};
}]);
答案 0 :(得分:1)
比较post id,比较对象不是一个好主意,IMO。所以现在你不需要发送remPost
作为参数
$http.put('/posts/' + postid, input).success(function (data, status) {
for (var i = 0, ii = $scope.posts.length; i < ii; i++) {
if ($scope.posts[i].id === postid) {
$scope.posts[i] = data;
}
}
});
答案 1 :(得分:0)
以下函数适用于我,remPost是ng-repeat中的post对象。如果有人有更有说服力的解决方案,我很乐意听到它
$scope.toggleStatus = function (postid, status, remPost) {
var input = {};
console.log(remPost);
if (status === 'DRAFT') {
input.status = 'APPROVED';
}
if (status === 'APPROVED') {
input.status = 'DRAFT';
}
$http.put('/posts/' + postid, input).success(function (data, status) {
for (var i = 0, ii = $scope.posts.length; i < ii; i++) {
if ($scope.posts[i] === remPost) {
$scope.posts[i] = data;
}
}
});
};