下面的代码来自 Angular 应用程序中的聊天界面。用户将通过单击用户气泡来选择他们希望向其发送消息的用户,这会将这些用户添加到数组selectedChatUsers
列出用户。突出显示当前选择的那些。
<div ng-repeat="user in PlayerController.chatUsers | orderBy:['type','name']"
class="chat-recipient"
ng-class="{'selected-recipient' : PlayerController.selectedChatUsers.indexOf(user) >= 0 }"
ng-click="PlayerController.selectRecipient(user)">
<div class="chat-recipient-name" ng-bind="user.name"></div>
<div class="chat-recipient-icon"></div>
</div>
该应用程序的另一个功能是能够单击已发送消息中的聊天气泡,并使用“to”属性填充selectedChatUsers数组,该属性是该消息发送到的用户数组。
此功能有效,但应该显示这些用户被选中的 ng-class 指令不起作用。
function chatReply(message){
/* one attempt was to try and manipulate the array rather than copy the information directly. This attempt had no more success. I'm including it here just to show that it was tried */
/****
self.selectedChatUsers.length = 0;
angular.forEach(message.to, function(recipient){
self.selectedChatUsers.push(recipient);
});
****/
/* Also tried wrapping the whole thing in $timeout and $scope.$apply, this also doesn't update the ng-class in the view */
$timeout(function() {
$scope.$apply(function(){
self.selectedChatUsers = angular.copy(message.to);
});
});
}
关于如何在 selectedChatUsers 更改时更新视图中的 ng-class 的建议?