Marlene Tourn
Marlene Tourn

Reputation: 3

AngularJS ng-repeat and ng-style is applying the style in all the boxes

I'm trying to make 4 buttons with values = "red", "green", "blue" and "yellow", which when I click them display a box with the respective background-color. The problem is that the background-color applies to all the boxes, not just in their respective. I tried this in view:

<div class="cont">
<div class="botones">
    <button ng-click="agregarColor(0)" class="btninter" style="color: red">Rojo</button>
    <button ng-click="agregarColor(1)" class="btninter" style="color:green">Verde</button>
    <button ng-click="agregarColor(2)" class="btninter" style="color:blue">Azul</button>
    <button ng-click="agregarColor(3)" class="btninter" style="color:yellow">Amarillo</button>
</div>
<div class="cajamuestra">
    <div ng-style="change" class="cajacolor" ng-repeat="clr in repeats track by $index">
        {{clr}}
    </div>
</div>

and this in the controller:

.controller("MiControlador", function($scope){
$scope.colores = ["Rojo", "Verde", "Azul", "Amarillo"];
$scope.repeats = [];
$scope.agregarColor = function(i){
    $scope.repeats.push($scope.colores[i]);
    if (i==0){
        $scope.change = {
            "background-color" : "rgba(255,0,0,0.5)"
        }
    } else if (i==1) {
        $scope.change = {
            "background-color" : "rgba(0,255,0,0.5)"
        }
    } else if (i==2) {
        $scope.change = {
            "background-color" : "rgba(0,0,255,0.5)"
        }
    } else if (i==3) {
        $scope.change = {
            "background-color" : "rgba(255,255,0,0.5)"
        }
    }
}

Upvotes: 0

Views: 75

Answers (1)

logee
logee

Reputation: 5067

That's because there is only 1 change value defined in $scope. You will need a change variable for each repeat.

$scope.agregarColor = function(i){
    var clr = {
       color: $scope.colores[i]
    };
    
    if (i==0){
        clr.change = {
            "background-color" : "rgba(255,0,0,0.5)"
        }
    } else if (i==1) {
        clr.change = {
            "background-color" : "rgba(0,255,0,0.5)"
        }
    } else if (i==2) {
        clr.change = {
            "background-color" : "rgba(0,0,255,0.5)"
        }
    } else if (i==3) {
        clr.change = {
            "background-color" : "rgba(255,255,0,0.5)"
        }
    }

    $scope.repeats.push(clr);
}

and your repeat to this:

<div ng-style="clr.change" class="cajacolor" ng-repeat="clr in repeats track by $index">
    {{clr.color}}
</div>

Upvotes: 0

Related Questions