Generating variable for ng-class dynamically using

2020-03-12 03:44发布

问题:

Here is snippet from my HTML code.

<div ng-repeat="boxName in boxNameList">
    <div ng-class="myBoxes.{{boxName}}">{{boxName}}</div>
</div>

What I am trying to do: I have created 3 div elements which will be at the top of a screen using the above written snippet. Each div element will be given a shape of a box using css. A box(div) can have either red color as its background or black color as its background.

CSS for the two colors is:

.redBackground{
   background-color: red;
}

.blackBackground{
  background-color: black;
}

Here is a snippet from my controller:

$scope.boxNameList=['Box1','Box2','Box3'];
$scope.myBoxes={
      Box1: "redBackground",
      Box2: "blackBackground",
      Box3: "blackBackground"
}

In this example I have made $scope.myBoxes as a static Json but at runtime I plan to generate Json code so that I can dynamically assign background colors to my boxes.

Problem that I am facing: Well the problem is that I am not able to see the boxes with colors at all. The ng-class variable name in this case as you can see is also generated dynamically. If I do not use ng-repeat and do not dynamically generate ng-class variable name then it works fine. For e.g for the snippet given below when I dynamically change the value of the varibales myBoxes.Box1 myBoxes.Box2 and myBoxes.Box3 then it works perfectly.

<div ng-class="myBoxes.Box1">Box1</div>
<div ng-class="myBoxes.Box2">Box2</div>
<div ng-class="myBoxes.Box3">Box3</div>

However if I generate the ng-class variable dynamically "myBoxes.{{boxName}}" then it doesn't behave like a variable. I am sure there would be a better way to achieve what I am trying to do however I was not able to find that after hours and hours of googling/trial and error. Would be glad if someone could help me.

回答1:

You're almost there, it's myBoxes[boxName] and not myBoxes.{{boxName}}.

Something like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.controller('MainCtrl', ['$scope', function($scope){
        $scope.boxNameList=['Box1','Box2','Box3'];
        $scope.myBoxes={
              Box1: "redBackground",
              Box2: "blackBackground",
              Box3: "blackBackground"
        }
    }]);
    </script>
    <style type="text/css">
    .redBackground{
       background-color: red;
    }

    .blackBackground{
      background-color: black;
    }
    </style>
</head>
<body ng-controller="MainCtrl">
    <div ng-repeat="name in boxNameList">
        <div ng-class="myBoxes[name]">Box1</div>
    </div>
</body>
</html>