Ilya Buziuk Ilya Buziuk - 10 months ago 36
AngularJS Question

What is the right way of passing array between scopes using two-way data binding in Angular?

Assuming that there is an angular custom directive which uses an isolated scope for array object with two-way binding:

// scope values
this.scope = {
myArray: '='

So, now if I will add objects to the array everything will work like a charm:

myArray.push(item); // array in the parent scope will be updated

However, when I will try to remove object from array via slice method it will not work - array will remain to be the same:

myArray.slice(itemIndex, 1); // ERROR: array will remain to be the same - item will not be deleted

Basically, slice creates a new array object which, as I understand, is prohibited by angular. So, the question is - what is the right way of passing array between scopes via two-way data binding with an ability of adding / removing objects ?

Answer Source

Reading the documentation for Array.slice:

slice does not alter. It returns a shallow copy of elements from the original array.

Also of note, the first argument is the starting index, and the second argument is the ending index. To actually change your scope variable, you need to assign the return value like so:

myArray = myArray.slice(itemIndex, itemIndex+1);

More likely, you are looking to directly manipulate your array. Use Array.splice (that's splice with a p) to remove elements from the array.

myArray.splice(itemIndex, 1);