N G N G - 1 year ago 91
Javascript Question

AngularJs directive view not updating on ng-repeat

I have directive with ng-repeat inside. And I have toggle function inside that changing order of array items. When I'm displaying scope model I see that items changing their order but UI not updating. Tried scope.$apply() but it says that process busy.

.directive('example', function() {
return {
restrict: 'E',
transclude: true,
template: `
Checking model: {{model}}

<div ng-repeat="(key, row) in model">
<div ng-hide="key == 0">
<div class="icon-arrow-u" ng-hide="$first" ng-click="moveUp(key)"></div>
<div class="icon-delete" ng-click="removeCell(key)"></div>
<div class="icon-arrow-d" ng-hide="$last" ng-click="moveDown(key)"></div>
scope: {
model: '='
link: function(scope, element) {
scope.moveItem = function (origin, destination) {
var temp = scope.model[destination];
scope.model[destination] = scope.model[origin];
scope.model[origin] = temp;

scope.moveUp = function(index) {
scope.moveItem(index, index - 1);

scope.moveDown = function(index) {
scope.moveItem(index, index + 1);

Answer Source

Without seeing a code fiddle, I'd guess that the reason lies within the ng-repeat directive. You should add a track by expression (see AngularJS doc)

For example you could write (key, row) in model track by key or (key, row) in model track by row. Either way it has to be a value that's unique to every row.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download