【发布时间】:2016-05-26 09:27:10
【问题描述】:
在页面上我有ng-repeat,它遍历集合中的项目。每个项目都有属性status,根据它我添加或不添加一些类。并且每个item都有按钮,点击它可以改变item状态并向API发出PUT请求。
由于我在页面上的收藏每 2 分钟更新一次,因此在几次更新后我遇到了问题。 5-6 分钟后,我单击按钮,这使 PUT 请求(成功),但我的 ng-class 函数没有检测到项目的 status 已更改。
<div class="one-third" ng-repeat="request in requests track by request.id">
<div class="incoming_request" ng-class="actionClass(request)">
<h2 ng-class="DayTypesClasses[request.typeId]" ng-bind="request.type"></h2>
<hr>
<div class="request_description">
<p><span>Description:</span></p>
<p ng-bind="request.baseComment"></p>
</div>
<div class="request_resolve">
<hr>
<div class="textarea-holder">
<textarea placeholder="Your comment..." ng-model="request.newComment" ng-model-options="{ updateOn: 'default blur'}"></textarea>
</div>
<div class="button-container">
<button ng-click="approve(request);" class="btn btn-primary">Confirm</button>
<button ng-click="reject(request);" class="btn btn-default pull-right" am-hide-request-resolve-div>Reject</button>
</div>
</div>
</div>
</div>
和 JS 代码
$scope.approve = function (request) {
var status = State.APPROVED;
var currentUserComment = request.comments.filter(function(comm) {
return comm.userId == user.id && comm.status == "Pending";
})[0];
currentUserComment.status = status; //change status
currentUserComment.text = request.newComment;
delete request.newComment;
if (!currentUserComment) {
request.isProcessing = false;
return;
}
Comments.update(currentUserComment, function() {
// $rootScope.$broadcast('daysUpdated');
});
request.isProcessing = false;
};
Ng-class函数:
$scope.actionClass = function(request) {
var currentUserComment = request.comments.filter(function(comment) {
return comment.userId == user.id;
})[0];
//after click here status for every item isn't changed. Tested in debug mode
if (!currentUserComment || currentUserComment.status == State.APPROVED || currentUserComment.status == State.REJECTED) {
return 'you-approved';
}
}
因此,在对我的集合(我的意思是requests 集合)进行几次更新后,onclick js 无法添加类you-approved。
我错过了一个重要的细节 - 我将状态更改为项目 request,而不是项目,它存在于 request.comments。所以我不能只写ng-class="{'you-approved': request.approved}"
正如@Cyril 建议的那样,我尝试在我的控制器中使用这种和平的代码
$scope.$apply(function(){$scope.requests = CurrentUserData.getRequests();}) 但收到错误$digest already in progress。
我还尝试使用 angualr 服务 $interval 而不是 window.setInterval 函数,该函数每 2 分钟更新一次集合 requests,但它似乎没有帮助。
【问题讨论】:
-
你说的是
As my collection on page is updated every 2 minutes那么这是一个超时功能吗?每 2 分钟发生一次。 -
@Cyril,我有服务,它使用 setInterval 函数。这就是集合的更新方式
-
好的,所以当您在服务中获取数据时,您会更新应用块中的范围数据。
$scope.$apply(function(){$scope.data = newData;}) -
@Cyril - 我拥有的是每 2 分钟更新一些
requestResources集合的函数,Factory,它返回requestResources和 Controller,它将数据从 Factory 绑定到集合,我在ng-repeat:$scope.requests = CurrentUserData.getRequests(); -
@Cyril,我已将此代码添加到 Controller,但收到错误
$digest already in progress
标签: javascript angularjs put ng-class