【发布时间】:2016-07-21 18:44:26
【问题描述】:
我正在尝试创建干函数来添加和删除数组中的项目。对于可编辑的表格很有用。这需要使用 lodash 的 _.whithout 将对象和数组传递给函数,这样每当需要从表(或一般的数组)中删除一行时,只需传递要删除的对象和要从中删除的数组。
问题
在函数中定义数组可以正常工作。对象被移除并更新 DOM。将数组作为参数传递不会。对象已移除,但 DOM 未更新。
假设
Angular 正在解除对数组的绑定。
知道如何保持数组参数绑定吗?
代码如下:
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
}
//console.log(foo)
$scope.items.push(foo);
console.log($scope.items)
};
$scope.addItemUndef = function(item, array) {
thing = {
value: item
}
array.push(thing);
console.log($scope.items)
};
$scope.removeItemDef = function(obj) {
console.log('Before')
console.log($scope.items)
// var itemWithId = _.find($scope.items, function(item) {
// return item.value == obj.value;
// });
$scope.items = _.without($scope.items, obj);
console.log('After')
console.log($scope.items)
};
//This is the function that does not work
$scope.removeItemUndef = function(obj, array) {
console.log('Before')
console.log(array)
console.log($scope.items)
// var itemWithId = _.find(array, function(item) {
// return item.value == obj.value;
// });
array = _.without(array, obj);
console.log('After')
console.log(array)
console.log($scope.items)
};
};
【问题讨论】:
标签: javascript arrays angularjs lodash