0

I have looked at a number of StackOverflow articles to try and find out why my $watch is not working and most of them are citing the fact that either people are not updating Objects, or that the third parameter, the Object Equality operator is not set to true as specified in these articles here:

$watch not firing on data change

$watch is not working when model is updated in scope.$apply in directive

Here is my code:

Controller:

$scope.selectionPending = [];

// helper method to get selected friends
$scope.selectedFriends = function() {
  return filterFilter($scope.currentUser.friends, { requested: true });
};

// watch friends for changes
$scope.$watch('currentUser.friends|filter:{requested:false}', function (nv, ov) {
  console.log("Nv: ", nv);
  if(nv){
    console.log("$scope.selectPending: ", $scope.selectionPending);
    $scope.selectionPending = nv.map(function (friend) {
      return friend;
          //This is just an example of what my friend object may look like:
          /* Example Friend Object just to show what is inside this object
             {
             'requested': false,
             'pending': true,
             'username': "Test"
              }; */
    });
  }
}, true);

$scope.addPendingFriend = function(){
  console.log("SelectionPending: ", $scope.selectionPending);
  //Problem: Nothing is printing out: my selectionPending array is empty.
  ...
}

HTML File:

  <label ng-repeat="friend in currentUser.friends" ng-if="friend.pending == true">
    <input
      type="checkbox"
      name="selectedFriends[]"
      value="{{friend.requested}}"
      ng-model="friend.requested"
    > {{friend.username}}
  </label>
    <div>
      <button type = "button" class="btn btn-primary" ng-click="addPendingFriend()" ng-class="{'btn-default': friend.friendsToAdd, 'disabled': !friend.friendsToAdd}">
        {{friend.friendAddText}}
      </button>
    </div>

Basically I have some checkboxes inside my UI that I display with an ng-repeat and when I select a checkbox, I store in that object into the $scope.selectPending array. This works fine, but when I try to actually access any variables using my function $scope.addPendingFriend() my $scope.selectPending array is empty. I tried to add in the $scope.$apply function right after the return friend statement but I get an issue saying that the digest cycle is still in progress. I added in the 3rd parameter which to my knowledge, should perform a copy from my currentUser.friends array to my selectionPending array. I'm not really too sure why, can anyone help me out? Thanks!

Community
  • 1
  • 1
user1567909
  • 1,450
  • 2
  • 14
  • 24

1 Answers1

1

Try using $watchCollection instead of $watch hopefully that should work

Coder John
  • 776
  • 4
  • 7