简体   繁体   中英

ng-class not updating inside of ng-repeat when array is changed

The code below is from a chat interface in an Angular application. The user will select the users they wish to send the message to by clicking on user bubbles which will add those users to an array selectedChatUsers

Lists out the users. Highlights the ones that are currently selected.

<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>

Another feature of the application is the ability to click on a chat bubble from a sent message, and have the selectedChatUsers array be populated with the "to" property, which is an array of users that this message was sent to.

This functionality works, but the ng-class directive that should show those users are selected, does not function.

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);
           });
       });  

 }

Suggestions on how I can make the ng-class in the view be updated when selectedChatUsers is changed?

Both class and ng-class will not work together, always apply class :

class="chat-recipient"
ng-class="{'selected-recipient' :  condition }"

remove class and change it to:

 ng-class="condition == true ? 'chat-recipient selected-recipient' : 'chat-recipient'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM