Skip to content

Instantly share code, notes, and snippets.

@zomdar
Forked from jfornoff/Angular_array_movement.js
Created June 16, 2017 03:20
Show Gist options
  • Save zomdar/24c58cac060a970d19c451dc25c275cd to your computer and use it in GitHub Desktop.
Save zomdar/24c58cac060a970d19c451dc25c275cd to your computer and use it in GitHub Desktop.
This is some common element moving functionalitywithin JS Arrays, packaged in a Angular.js factory
app.factory('ArrayService', function(){
return {
deleteElement: function(array, element) {
var index = array.indexOf(element);
if(index == -1){
return false;
}
array.splice(index, 1);
},
moveElementUp: function(array, element) {
var index = array.indexOf(element);
// Item non-existent?
if(index == -1){
return false;
}
// If there is a previous element in sections
if(array[index-1]){
// Swap elements
array.splice(index-1,2,array[index],array[index-1]);
}else{
// Do nothing
return 0;
}
},
moveElementDown: function(array, element) {
var index = array.indexOf(element);
// Item non-existent?
if(index == -1){
return false;
}
// If there is a next element in sections
if(array[index+1]){
// Swap elements
array.splice(index,2,array[index+1],array[index]);
}else{
// Do nothing
return 0;
}
}
}
});
// Just use this within your controllers, don't forget to inject ArrayService into your controller!
// Locates elementWithinArray and deletes it, returns false on error.
ArrayService.deleteElement(myArray, elementWithinArray);
// Swaps elementWithinArray with element before it. Returns false on error.
ArrayService.moveElementUp(myArray, elementWithinArray);
// Swaps elementWithinArray with element after it. Returns false on error.
ArrayService.moveElementDown(myArray, elementWithinArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment