배열의 각도 변화를 관찰하는 방법JS
기본적으로 Backbone의 컬렉션에서 '추가' 및 '삭제' 이벤트에 대한 바인딩과 동등한 것을 원합니다.기본적으로 AngularJS에서는 이 작업을 수행할 방법이 없습니다. 현재 해결 방법은 다음과 같습니다.$watch()어레이 입력length모든 것을 수동으로 분산/계산합니다.이게 정말 멋진 애들이 하는 일인가요?
편집: 특히 어레이의 길이를 보면 변경된 요소를 쉽게 알 수 없으므로 수동으로 "diff"해야 합니다.
를 사용하는 것이 좋은 해결책이라고 생각합니다만, 자세한 비교는 실시하지 않고, 인서트, 삭제, 정렬등의 어레이의 변경(항목의 갱신은 실시하지 않습니다)만을 실시합니다.
예를 들어 속성을 유지하려면order어레이 순서와 동기화:
$scope.sortableItems = [
{order: 1, text: 'foo'},
{order: 2, text: 'bar'},
{order: 3, text: 'baz'}
];
$scope.$watchCollection('sortableItems', function(newCol, oldCol, scope) {
for (var index in newCol) {
var item = newCol[index];
item.order = parseInt(index) + 1;
}
});
다만, 고객의 문제에 대해서는, 수동으로 어레이를 참조해 변경을 특정하는 것보다 좋은 솔루션이 없는지를 알 수 없습니다.
Angular에서 배열을 보는 방법은$watch(array, function(){} ,true)
어린이 스코프를 만들어 개별적으로 봅니다.다음은 예를 제시하겠습니다.
$scope.myCollection = [];
var addChild = function()
{
var Child = $scope.$new();
Child.name = 'Your Name here';
Child.$watch('name', function(newValue) {
// .... do something when the attribute 'name' is changed ...
});
Child.$on('$destroy', function() {
//... do something when this child gets destroyed
});
$scope.myCollection.push(Child); // add the child to collection array
};
// Pass the item to this method as parameter,
// do it within an ngRepeat of the collection in your views
$scope.deleteButtonClicked = function(item)
{
var index = $scope.myCollection.indexOf(item); //gets the item index
delete $scope.myCollection[index]; // removes the item on the array
item.$destroy(); // destroys the original items
}
사용 사례에 대해 자세히 알려 주십시오.요소 지연을 추적하는 솔루션 중 하나는 요소의 $destroy 이벤트를 수신하는 커스텀 디렉티브와 함께 ngRepeat 디렉티브를 사용하는 것입니다.
<div ng-repeat="item in items" on-delete="doSomething(item)">
angular.module("app").directive("onDelete", function() {
return {
link: function (scope, element, attrs) {
element.on("$destroy", function () {
scope.$eval(attrs.onDelete);
});
}
}
});
백본과 같이 수집 클래스를 만드는 것이 해결책일 수 있습니다.또한 이벤트에 쉽게 접속할 수 있습니다.
여기서의 해결방법은 그다지 포괄적이지 않지만, 대략적인 가이던스를 제공해 드릴 것입니다.
http://beta.plnkr.co/edit/dGJFDhf9p5KJqeUfcTys?p=preview
언급URL : https://stackoverflow.com/questions/15681801/how-to-watch-an-array-for-changes-in-angularjs
'source' 카테고리의 다른 글
| wordpress fishpig magento 설치 - getPostListHtml() (0) | 2023.03.04 |
|---|---|
| Postgres의 json 개체에서 키, 값 추출 (0) | 2023.03.04 |
| Angular에서 함수 호출같은 서비스의 JS 서비스? (0) | 2023.03.04 |
| 부울값을 React의 소품으로 전달할 수 없는 이유는 항상 내 코드에 문자열이 전달되어야 하기 때문입니다. (0) | 2023.03.04 |
| 문서 배열의 개체를 업데이트하려면 어떻게 해야 합니까(내포된 업데이트) (0) | 2023.03.04 |