How to apply saved CSS code within an array using Angularjs?

Asked

Viewed 89 times

1

I am making a web game with different levels and need to change the style of a div using a code saved within an array in Angularjs. In addition, the game has a split on the screen, where in one half the user enters the code and in the other, appears the result. Each level has a different style for the background view, so it needs to be loaded every time.

The HTML file part is as follows:

<div id="background"></div>

And the code referring to the style is as follows:

$scope.css = [
    {
        'estilo': 'background-image : url(...); ...'
    }
];

Another tested form already:

$scope.css = [
    {
        //nível 1
        'background-image': 'url(...)',
        'position' : 'absolute',
         ...
    },
    {
        //nível 2
        ...
    }
];

However I am not able to display the result in the view. Nothing appears. I tried to add ng-style="{{css}}" à div but it didn’t work. What is the correct way to do this style assignment?

1 answer

1


I think it would be easier for you to create the style you want inside the file .css.

And to validate on HTML there is the directive in Angularjs called ng-class where you can assign a style with due condition... Example:

In your CSS file

.classe1 {
   background-color: red;
   border: 1px solid black;
}

.classe2 {
   background-color: green;
   border: 1px solid black;
}

in your HTML would validate the div thus:

<div ng-class="condição ? 'classe1' : 'classe2"></div> 

I used a if ternario where its structure is :

Condiçao ? se true executa aqui : se false executa aqui ;

example:

 1 == 1 ? console.log('verdade') : console.log('false');

in the case of your HTMLif its condition is true will assign the Classe1 to the div otherwise it will be assigned to class2

  • Mine was just the place where I inserted the ng-controller. It’s working perfectly, thanks for the help. Anyway, I managed to do it this way: ng-class="{'level-one': cur_level == '1', 'level-two': cur_level == '2', 'level-three': cur_level == '3'}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.