0

I have three arrays in a controller:

  1. $scope.allUsers containing all users by :id and :name. E.g. smth like this.
  2. $scope.job.delegated_to containing information related to job delegation. Looks like this.
    $scope.job.delegated_to = [
      {id: 5, user_id:33, user_name:"Warren", hour_count:4},
      {id: 5, user_id:18, user_name:"Kelley", hour_count:2},
      {id: 5, user_id:10, user_name:"Olson", hour_count:40},
      {id: 5, user_id:42, user_name:"Elma", hour_count:2},
      {id: 5, user_id:45, user_name:"Haley", hour_count:4},
      {id: 5, user_id:11, user_name:"Kathie", hour_count:3}
     ]
  1. $scope.freeUsers which has to contain all the users, not delegated to the job.

I added a watch

$scope.$watch('job.delegated_to.length', function(){
  $scope.freeUsers = filterUsers( $scope.allUsers, $scope.job.delegated_to );
});

but have not been able to construct a working filter.

3
  • While @dubadub answers the OP question correctly, I think the OP might have meant something else: using an angular $Filter that can be used on an ng-repeat directive. @Almaron can you clarify? Commented Jun 6, 2014 at 9:09
  • @alonisser, either way is fine. Whichever does the job. Commented Jun 6, 2014 at 9:36
  • just notice that this kind of filter can be used only in the controller. if you want to use it in template with ``` ng-repeat freeUsers | nonAssignedUsers``` you'll have to encapsulate one of the suggested filters within an angular $Filter Commented Jun 6, 2014 at 9:39

2 Answers 2

3

Your filterUsers function would be like:

var filterUsers = function(allUsers, jobs) {
    var freeUsers = allUsers.slice(0); //clone allUsers
    var jobUserIds = [];
    for(var ind in jobs) jobUserIds.push(jobs[ind].user_id);
    var len = freeUsers.length;
    while(len--){
      if(jobUserIds.indexOf(allUsers[len].id) != -1)  freeUsers.splice(len, 1);
    }    
    return freeUsers;
}

Checkout fiddle http://jsfiddle.net/cQXBv/

Sign up to request clarification or add additional context in comments.

Comments

2

I would suggest using a library like Lo-Dash, which has many useful utility functions. You could then write your filter function as:

function filterUsers(allUsers, delegatedTo) {
    var delegatedIndex = _.indexBy(delegatedTo, 'user_id');
    return _.reject(allUsers, function(user) {return user.id in delegatedIndex});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.