Search code examples
angularjsng-class

ng-class doesn't always work with dynamic content until page is refreshed


I have a directive that uses a template that is nested in an ng-repeat. I am using different themes for the items on this directive (just different class names) that can be changed by the user when they change the theme of the overall site. This functionality sometimes doesn't work when the user makes a theme change...unless they've refreshed the page at some point in which case it ALWAYS works when they make a theme change. This is such strange behavior that I'm not really even sure where to start troubleshooting. Here is the div where the class is set inside my directive template:

<div class="my-item" ng-class="[ma.getTheme(), ma.getSize()]">
...
</div>

here is the getTheme() function on the directive JS file:

function getTheme() {
            console.log('theme'+ma.item.themeId);
            return "theme" + ma.item.themeId;
        }

and here is the function on the controller JS file to change the theme:

function changeTemplate(selectedTemplate) {
...
for (var i = 0; i < ma.myItems.length; i++) {

                var item= ma.myItems[i];
                item.themeId = classes[index];

                var nextIndex = index + 1;
                if (nextIndex === classes.length) {
                    index = 0;
                } else {
                    index++;
                }
            }
}

where classes is just an array of different class numbers that get appended to the theme class name from the getTheme() function.

As I said above, this only fails when the page is first loaded (and not even always then). When the page is refreshed, it always works.

What would change with a page refresh that would cause this to work?

TIA


Solution

  • This has the look of a race condition to me. Like you're assigning content to something being returned by an ajax request, and sometimes the request completes in time, other times it doesn't. I would expect it works on refresh more reliably because the ajax request has been cached, and therefor resolves faster.