My goal is to create reusable functions for adding and removing items from arrays, particularly for editable tables. To achieve this, I pass an object and array to a function using lodash's _.without
method. This way, when a row needs to be removed from a table (or any array), I simply pass the object to remove and the corresponding array.
The Problem
When I define the array within the function, everything works as expected - the object is removed, and the DOM is updated accordingly. However, when passing the array as a parameter, the object is removed but the DOM does not update.
Potential Explanation
I suspect that Angular might be unbinding the array passed as a parameter.
Any suggestions on how to maintain the binding of the array parameter?
Take a look at the JSFiddle here
Below is the code snippet:
HTML
<table ng-controller="Ctrl">
<thead>
<tr>
<th>
<input ng-model="newItem" type="number">
</th>
<th>
<button type="button" ng-click="addItemDef(newItem)">Add - Array Defined</button>
</th>
<th>
<button type="button" ng-click="addItemUndef(newItem, items)">Add - Array Undefined</button>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.value}}</td>
<td>
<button type="button" ng-click="removeItemDef(item)">Remove - Array Defined</button>
</td>
<td>
<button type="button" ng-click="removeItemUndef(item, items)">Remove - Array Undefined</button>
</td>
</tr>
</tbody>
</table>
Javascript
function Ctrl($scope) {
$scope.items = [{
value: 5
}];
$scope.addItemDef = function(item) {
foo = {
value: item
}
$scope.items.push(foo);
};
$scope.addItemUndef = function(item, array) {
thing = {
value: item
}
array.push(thing);
};
$scope.removeItemDef = function(obj) {
$scope.items = _.without($scope.items, obj);
};
$scope.removeItemUndef = function(obj, array) {
array = _.without(array, obj);
};
};