Pregunta

Plunker - http://plnkr.co/edit/jXdwOQR2YLnIWv8j02Yp

I'm using angular to build a view which has a list of users in the main container (array-A) and a sidebar of users which host any 'selected' users (array-B).

The first one (A) has all the users.

[{ $$hashKey: "00F", id: "118207f5e52c3eb619a8760bc08c8224", username: "John Smith" }, { $$hashKey: "00G", id: "9c2d6f31c88e7a654e64bd0d3371360a", username: "Fredy Rincon" }, { ... }]

The second one (B) has the users that are already selected (Firebase db) and through which the sidebar is pre-populated. If the users are already selected then they appear here exactly as they do in array-A.

My goal is to be able to add and remove objects from array-B / Sidebar view, by clicking on items from array-A in the main container.

The below is as close as I've been able to get but it doesn't take into account the existing users which are pre-populated onto the sidebar, and just adds and removes items that are already present, as if they weren't there.

For your reference:

$scope.selectedUsers = array-B

user = object in array-A

$scope.selectUser = function (user) {
  console.log($scope.selectedUsers.indexOf(user))
  if ($scope.selectedUsers.indexOf(user) === -1 ) {
    $scope.selectedUsers.push(user);
    console.log($scope.selectedUsers);
  } else {
    $scope.selectedUsers.splice($scope.selectedUsers.indexOf(user), 1);
    console.log($scope.selectedUsers);
  }
};

I really have no idea as to how to approach a solution for this, would really appreciate any help possible.

Thanks.

¿Fue útil?

Solución

Use Array.prototype.reduce to check users before adding:

$scope.add = function(user){
  var match = $scope.selectedUsers.reduce(function(prev, curr) {
    return (user.id === curr.id) || prev;
  }, false);
  console.log(match ? 'match' : 'no match');
  if (!match) $scope.selectedUsers.push(user);
};

... where your view looks like:

<p ng-repeat="user in users">{{user.username}} <a ng-click="add(user)">+</a></p>

To remove users from the selectedUsers array, use Array.prototype.splice:

$scope.remove = function(index){
  $scope.selectedUsers.splice(index, 1)
}

...where your view looks like:

<p ng-repeat="selectedUser in selectedUsers">{{selectedUser.username}}
<a ng-click="remove($index)">--</a></p>

Working Plunker

Otros consejos

Since it appears that each of your objects has a unique string ID, a viable approach is to store only the IDs in array-A and array-B, store a dictionary of the full data objects in a shared service, and use an angular filter to look up the full data object by ID when needed for presentation, etc.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top