Reputation: 71
I'm creating a web game with different levels and need to change a div style using code stored inside an array in AngularJS. The game has two screens: the left one the user types the code in HTML and, the right one shows the result. This screen has a background and a div with the element created by the code. Each level has a different style for the background, so it needs to be loaded when the user changes the current level.
The HTML code is as follows:
<div id="background" ng-class="css"></div>
And the code in AngularJS is:
$scope.css = [
{
//level one
'background-image': 'url(url1)',
'position' : 'absolute',
...
},
{
//level two
'background-image': 'url(url2)',
...
}];
Another approach is to use a variable called $scope.cur_level
that I'm using get number of current level to use it in ng-class
with conditions:
ng-class="cur_level = '0' ? 'level_one' : 'level_two'"
In this case, each level style was created in the CSS file. However, the style of the first level is loaded for every level. I really want use the array approach. What is the best way to do this?
Upvotes: 0
Views: 321
Reputation: 627
Here's the correct way of using the ng-class directive:
(function () {
"use strict";
const app = angular.module("app", []);
app.controller("app.GameCtrl", $scope => {
$scope.currentLevel = "1";
$scope.setLevel = () => {
$scope.currentLevel = $scope.currentLevel === '1' ? '2' : '1';
};
}
);
})();
.container {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20px;
width: 100px;
height: 100px;
color: #FFF;
font-size: 3em;
}
.level-one {
background-color: red;
}
.level-two {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="app.GameCtrl">
<div class="container" ng-class="{'level-one': currentLevel === '1', 'level-two': currentLevel === '2'}">
{{currentLevel}}
</div>
<a href="" ng-click="setLevel();">Change Level</a>
</div>
Upvotes: 0