我有非常简单的代码这是正常工作我的问题是我无法改变喜欢不喜欢和不喜欢div
<div class="posts" ng-repeat="s in newsFeeds">
{{s.message}}
<div ng-if="s.likeStatus === 1">
<div class="liked">
<a ng-click="unlikePost(s.id,s.userid)">liked</a>
</div>
</div>
<div ng-if="s.likeStatus === 0">
<div class="like">
<a ng-click="likePost(s.id, s.userid)">like</a>
</div>
</div>
</div>
我的方法
$scope.likePost = function (id, userid) {
var data = 'id=' + id + "&userid=" + userid;
console.log(data);
$http({
method: 'POST',
url: "like",
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(rs, status, headers, config) {
if (rs.data.st === 1) {
console.log("liked");
$scope.likeStatus = 0;
} else if (rs.data.st === 0) {
console.log("Sdfbb");
}
}, function errorCallback(data, status, header, config) {
alert("Opps unable to connect to server");
}
);
};
答案 0 :(得分:1)
如评论中所述,您需要像news一样对newsFeed中的每个项目进行正确跟踪,以便您可以执行以下操作:
<div class="posts" ng-repeat="s in newsFeeds">
{{s.message}}
<div ng-if="s.likeStatus === 1">
<div class="liked">
<a ng-click="unlikePost(s)">liked</a>
</div>
</div>
<div ng-if="s.likeStatus === 0">
<div class="like">
<a ng-click="likePost(s)">like</a>
</div>
</div>
</div>
和你的控制器一样:
$scope.likePost = function (item) {
var data = 'id=' + item.id + "&userid=" + item.userid;
$http({
method: 'POST',
url: "like",
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(rs, status, headers, config) {
if (rs.data.st === 1) {
item.likeStatus = 1;
} else if (rs.data.st === 0) {
console.log("error or something");
}
}, function errorCallback(data, status, header, config) {
alert("Opps unable to connect to server");
}
);
};
您需要更改与使用newsFeed对象的方法不同。像这样,你将每个项目和一个实体实体跟踪而不是多个。
另一个建议是将服务调用从控制器移到角度服务,以便更好地维护。
答案 1 :(得分:0)
这不起作用,因为在您的通话响应中$ scope.likeStatus = 0是通用的。您可以在函数中传递$ index变量,然后使用likeStatus构建一个数组:
1)传递$ index参数
<a ng-click="likePost(s.id, s.userid, $index)">like</a>
2)并在你的功能中
$scope.likePost = function (id, userid,index) {
var data = 'id=' + id + "&userid=" + userid;
console.log(data);
$http({
method: 'POST',
url: "like",
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(rs, status, headers, config) {
if (rs.data.st === 1) {
console.log("liked");
$scope.likeStatus[index] = 0;
} else if (rs.data.st === 0) {
console.log("Sdfbb");
}
}, function errorCallback(data, status, header, config) {
alert("Opps unable to connect to server");
}
);
};
3)更改你的ng-if
<div ng-if="likeStatus[$index] == 0">