ng-repeat not affected by clearing array

107 Views Asked by At

In html I'm repeating over an array of strings:

<div class="palette__record"
     data-ng-repeat="n in palette track by $index"
     data-ng-style="{'background-color':'#'+n}">
</div>

In controller palette is gathered from localForage (same as localstorage but async)

$localForage.getItem('palette')
    .then(colors => {
        if(colors) vm.palette = colors;
    });

This works fine, now after click button I'm "clearing" palette by seting it to [] in localForage then geting it again and seting value in controller:

vm.clearEntirePalette = () => {
    $localForage.setItem('palette', [])
        .then(() => {
            $localForage.getItem('palette')
                .then(colors => {
                    console.log('clear palette', colors);
                    if(colors) {
                        vm.palette = colors;
                    } else {
                        vm.palette = [];
                    }
                });
        });
};

Here as you can see I'm console loging to double check and it's fine it's empty array. Now since I always want my array to contain 8 elements (also when other operations on this array) I have $watch which is invoked after vm.palette = colors; from above.

vm.$watch('palette', newVal => {
    console.log('caught change');

    if(newVal.length < 8) {
        const fillArr =  new Array(8 - newVal.length);
        fillArr.fill('');
        vm.palette = vm.palette.concat(fillArr);
        console.log('after fill', vm.palette)
        //$scope.$apply();
    }
}, true);

This also works fine, after above code palette is array with 8 empty strings. However ng-repeat does not catch this change and doesn't update. I tried to use $scope.$apply() in $watch after fill but it cause error

[$rootScope:inprog] $digest already in progress

How to fix it so ng-repeat reflect array?

0

There are 0 best solutions below