If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code?
<div class="square red"></div>
<div class="square blue"></div>
<div class="square yellow"></div>
<div class="square green"></div>
To achieve this, I added an ng-class
triggered by a ng-click
for each field. Here's an example:
<div class="square red" ng-class="{'open':redSquare == true}" ng-click="clickRedSquare()"></div>
<div class="square blue" ng-class="{'open':blueSquare == true}" ng-click="clickBlueSquare()"></div>
<div class="square yellow" ng-class="{'open':yellowSquare == true}" ng-click="clickYellowSquare()"></div>
<div class="square green" ng-class="{'open':greenSquare == true}" ng-click="clickGreenSquare()"></div>
In the controller, the logic is implemented as follows:
$scope.redSquare = true;
$scope.clickRedSquare = function() {
$scope.redSquare = !$scope.redSquare;
$scope.blueSquare = false;
$scope.greenSquare = false;
$scope.yellowSquare = false;
};
// Repeat for other colors...
Is there a more optimal way in Angular to prevent duplicate code? You can check out the working plunkr here. Thank you!