Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: add, remove and reorder items controlled by array

I have an ng-repeat in a table. There are several of these tables inside a larger table. Each row has buttons for "add another" (which I have working) and remove current row/move row up-down (which I don't).

enter image description here

They are created with an array, each group in the table has its own array, with one member to start.

  vm.choices1 = [{ id: 'choice1' }];
  vm.choices2 = [{ id: 'choice1' }];
  vm.choices3 = [{ id: 'choice1' }];

Clicking the plus button passes the current array and pushes a new item onto it, thus adding a repeater.

vm.addNewChoice = function(arr) {
 var newItemNo = arr.length + 1;
  arr.push({
    'id': 'choice' + newItemNo
  });
};

This works fine. Of course, now I have been asked to add the delete button and up/down buttons.

I get in concept what I need to do: I suppose somehow when the delete button is clicked I need to pass that index number to a delete function and pop that index from the array thats passed:

vm.deleteChoice = function(arr) {
    arr.splice(index, index+1); //??
};

But I'm not sure how to get and pass the clicked index to the function. I used to know how to do this in jQuery, but not in Angular. If I can get the index of the clicked item into my function, I'm sure I can figure out the u/down buttons from there too.

Basic punker: http://plnkr.co/edit/WPdnmYbDSXC0LsbeMduM?p=preview

like image 658
Steve Avatar asked May 14 '26 06:05

Steve


1 Answers

The directive ng-repeat creates a scope for every item that it iterates through. Part of the data assigned to this scope is the attribute $index which will be equal to the index in the array of the item/object.

Source: https://docs.angularjs.org/api/ng/directive/ngRepeat

like image 96
Isaac Hinckley Avatar answered May 16 '26 21:05

Isaac Hinckley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!