سؤال

I'm new to AngularJS and i have the next issue. I'm calculating my CSS class of the body tag with ng-class like this.

<body ng-class="getCSSclassBody(Sucursal.SucursalEmpresaRubroNombre)">

The thing is that sometimes is rendering the HTML correctly, but sometimes class is empty. It seems like HTML is rendered faster than the evaluation of the function in the controller. Can anyone guide me on how to solve this problem?

    $scope.getCSSclassBody = function(rubro)
{
    if(rubro == 'Vestimenta'){
        var index = getRandomInt(0,arrayVestimenta.length);
        return arrayVestimenta[index];
    }
    else if(rubro == 'Peluquería'){
        var index = getRandomInt(0,arrayPeluqueria.length);
        return arrayPeluqueria[index];
    }
    else if(rubro == 'Gastronomía'){
        var index = getRandomInt(0,arrayGastronomia.length);
        return arrayGastronomia[index];
    }
    else if(rubro == 'Rentadora'){
        var index = getRandomInt(0,arrayRentadora.length);
        return arrayRentadora[index];
    }
}

Thanks in advice.

هل كانت مفيدة؟

المحلول

If the number generated by getRandomInt(0, arrayRentadora.length) is equal to arrayRentadora.length, then arrayRentadora[index] will be undefined.

For example, if arrayRentadora = ["Banana", "Orange", "Apple", "Mango"], the length is 4, and arrayRentadora[4] will be undefined.

To ensure you always choose a value from the array, you want this instead:

var index = getRandomInt(0, arrayRentadora.length - 1);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top