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

  3. $scope.freeUsers wich 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.

||||||
  • 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? – alonisser Jun 6 '14 at 9:09
  • @alonisser, either way is fine. Whichever does the job. – Almaron Jun 6 '14 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 – alonisser Jun 6 '14 at 9:39
  • @alonisser noted, thanks. – Almaron Jun 6 '14 at 9:43
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/

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.