ng-repeat
을 포함한 사용자 지정 지시문을 만들었습니다. 지시문에서 모델 업데이트를 트리거하면 ng-repeat
은보기에서 다른 것이 발생할 때까지 데이터 변경 사항을 표시하지 않습니다. 데이터가 올바르게 업데이트되었는지 확신합니다.AngularJS : ngRepeat가 사용자 지정 지시문에서 업데이트되지 않습니다.
컨트롤러 :
app.controller('myCTRL', ['$scope', function ($scope) {
//the 'model':
$scope.data=[];
for (var i = 0; i < 9; i++)
$scope.data.push({
'val':i+1,
'pos':i+1
});
$scope.directiveOptions = {
changeData: function (from, to) {
//here is the data update:
var tmp= $scope.data[from].val;
$scope.data[from].val =$scope.data[to].val;
$scope.data[to ].val =tmp;
}
};
$scope.revertData = function() {
for (var i = 0; i < 9; i++)
$scope.data[i].pos = $scope.data[i].pos * -1;
};
}]);
보기 :
<div ng-controller="myCTRL">
<div id="container" ng-my-directive='directiveOptions'>
<div ng-repeat="item in data | orderBy:'pos'" class="itemClass" >
<div>
{{item.val}}
</div>
</div>
</div>
<div ng-click="revertData()">revert</div>
</div>
지침 :
app.directive('ngMyDirective', function() {
return {
restrict: 'A',
scope: {
directiveOptions: '=ngMyDirective'
},
link: function (scope, elem, attr) {
//...
elem.on(
'mouseup',
function (e) {
// here I call the data change, but ng-repeat doesn't update
var from=2, to=3;
if (scope.directiveOptions.changeData){
scope.directiveOptions.changeData(from, to);
}
}
);
//...
}
};
});
경우에 코드입니다 revertData
div를 클릭하면 업데이트 된 데이터를 볼 수 있습니다. 나는 changeData
의 끝에 $apply()
을 강제로 넣거나 ng-repeat
에 비어있는 ng-mouseover=""
을 추가해야한다. 그러나 이것이 최선의 방법이라고 생각하지 않는다.
무엇이 누락 되었습니까?
을 편집 jQLite 이벤트 $ evalAsync를 사용하여 제안 @yarons로서
는 데이터 변경은 뷰 업데이트를 포함한다. 하지만 이것이 최선의 방법인지 확신 할 수 없습니다. 중첩 된 ng-repeat 지시문에서 $ scope 변수에 액세스하고 있습니다. 이 지시문은 모델에 영향을주는 DOM 조작을 구현합니다. 이것이 최선의 방법입니까?
당신은 이것을 위해 플 런커를 만들 수 있습니까? –
@AdityaSethi 여기에 두 가지 가능한 해결책이 있습니다. http://plnkr.co/edit/CF6ahi8g81NMhfV939l6?p=preview – ainos984