This code is the whole logic for the AngularJS ui-select lib. I'm not (yet) a JS pro and still learning AngularJS as well but I'm pretty sure this can be done a little more efficient? I'm talking especially about the search:
part of the object. In php I would probably do something like array_diff. Any critiques are welcome!
The reason for the selectedIds: []
is that I use ng-repeat to render a list of hidden fields with name="users[]"
to be able to fetch the list as a php array on the server side. I'm not suing Angular as a single page app here, I'm just using it for all the widgets but the data itself is submitted with the whole page as POST.
The for (var key in result.data)
is done to filter already selected ids out of the array. It was the most easy solution to avoid the error Duplicates in a repeater are not allowed.
. Sure I could pass the already existing ids to the lookup GET request but I think this works fine on the client side as well.
$scope.usersList = {
items: [],
selected: [],
selectedIds: [],
extractIds: function() {
$scope.usersList.selectedIds = [];
for (var i = 0; i < $scope.usersList.selected.length; i++) {
$scope.usersList.selectedIds.push($scope.usersList.selected[i].id);
}
},
select: function($item, $model) {
this.extractIds();
},
remove: function($item, $model) {
this.extractIds();
},
search: function(term) {
if (term.length > 2) {
UsersService.lookup(term).then(function(result) {
for (var key in result.data) {
if (result.data.hasOwnProperty(key)) {
if ($scope.usersList.selectedIds.indexOf(result.data[key].id) != -1) {
delete result.data[key];
};
}
}
$scope.usersList.items = result.data;
});
}
}
};
track by $index
. \$\endgroup\$