배열에서 항목을 추가 및 제거하기 위해 함수를 생성하려고합니다. 편집 가능한 테이블에 유용합니다. 이것은 lodash의 _.whithout
을 사용하는 함수에 객체와 배열을 전달하는 것을 의미하므로 테이블 (또는 일반적으로 배열)에서 행을 제거해야 할 때마다 제거 할 객체와 제거 할 배열을 전달하면됩니다.ng-repeat 객체 및 배열을 _.without을 사용하여 함수에 전달합니다.
기능의 배열을 정의 문제는
잘 작동합니다. 개체가 제거되고 DOM이 업데이트됩니다. 배열을 매개 변수로 전달하는 것은 아닙니다. 개체가 제거되었지만 DOM이 업데이트되지 않았습니다.
가설
코너 배열을 바인딩 해제된다.
어떤 방법으로 배열 매개 변수를 바인딩 할 수 있습니까? 여기
코드입니다 :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>
자바 스크립트
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)
};
};
바인딩을 유지하기 위해 올바르게 이해한다면 바인딩 된 배열에서 모든 것을 연결하고 _.without 결과로 채 웁니다. 그것은 흥미로운 해결책입니다. 나는 Lodash가 새로운 배열을 반환한다는 것을 잊었다. – davidcapatch
@davidcapatch, correct. 핵심은 전달 된 배열을 수정 (또는 기존'$ scope.items'를 이미'.removeItemDef'에서 작동하고 있던 복사본으로 덮어 씁니다.)해야한다는 것입니다. –