Conditional BG Color on AngularJS

- 1 answer

Ad

I am trying to make a page that shows offline and online twitch streams, and if the stream is online, I'd like it to display a darker color, however what I have isn't really working. I'm not 100% familiar with AngularJS, so any help would be appreciated.

All other entries that I have found stated to create css entries for each entry in the array, but the array is always changing and new ones being added. I can't keep adding in new separate styles for every streamer.

This is the part that is causing issues:

$.getJSON(url + 'streams/' + stream + cb).success(function(data) {
    var streaming = (data.stream === null) ? false : true;
    if (streaming) {
        obj.status = 'green fa fa-check';
        document.getElementById("'oncheck-' + user.username").style.backgroundColor = '#ccffcc';

        var streamTitle = data.stream.channel.game;
        if (streamTitle.length > 36) {
            streamTitle = streamTitle.substring(0,33);
            streamTitle += '...';
        }

        obj.streamTitle = streamTitle;

And then for the html part of the section I have:

 <li id="oncheck-{{user.username}}">
     <img ng-src="{{user.logo}}" err-src="images/twitch-default.jpg" class="pic"/>
     <span class="name">{{user.name}}</span>
     <span class="status"><i class="{{user.status}}"></i></span>
     <span id="offline" class="title">{{user.streamTitle}}</span>
 </li>

The id "oncheck-{{user.username}} works fine, but it's the part where I want to change the BG for that box if it's online that isn't.

Ad

Answer

Ad

The ng-style directive is made for stuff like this. Just assign the status/streaming value to your user object (or somewhere else) and use it in your template:

ng-style="{ 'background-color' : (user.streaming) ? 'green' : 'red' }"

https://docs.angularjs.org/api/ng/directive/ngStyle

If you find yourself wanting to apply more rules than one then you should take a look at ng-class, where you can conditionally apply classnames to elements:

https://docs.angularjs.org/api/ng/directive/ngClass

Edit after comments, here's an example using one variable to switch style and classes:

Controller:

 app.controller('MainCtrl', function($scope) {
     $scope.user = {
         streaming: false
     };
 });

Template:

 <li ng-style="{'background-color': (user.streaming) ? 'green': 'red'}">
     <i class="fa" ng-class="{'fa-check': user.streaming, 'fa-times': !user.streaming}"></i> User
 </li>

Example on Plunker: http://plnkr.co/edit/v5OFAG2x8E7dXbsWYtyX?p=preview

Ad
source: stackoverflow.com
Ad