Ryan - Llaver Ryan - Llaver - 1 year ago 137
AngularJS Question

Change CSS (or class) of an angular directive element based on data from ng-repeat

I have data coming from an ng-repeat in my main html

<span ng-repeat="acqui in acquis">
<card-info class="card" acqui="acqui"></card-info>

in my card-info directive (separate html file) I have a few elements that display the data

<h6 class="buyer">Acquired By: <strong>{{acqui.buyer.name}}</strong></h6>
<h2 class="seller">{{acqui.seller.name}}</h2>
<h1 id="value" class="value">{{acqui.value | shortNumber}}</h1>

I want to change the color of value if the value is undisclosed. I would prefer to just be able to change the class from "value" to "undis", but I would be okay with just overwriting the CSS and changing the color that way.

I have already tried a few ways, none of which have yet to be successful.

I tried detecting it in my directive:

acquisitionApp.directive('cardInfo', function() {
return {
restric: 'E',
scope: {
acqui: '='
link: function(scope, element, attrs) {
scope.$watch(attrs.cardInfo, function(value) {
if(value.value === "undisclosed") {
element.css("color", "#FF2100");
templateUrl: 'js/directives/card.html'


but value is undefined (I mean value, not value.value)

I also tried in my controller where I set the value to undefined in the first place

acquisitionApp.controller('acquiController', ['$scope','$http','acquiFactory', function($scope, $http, acquiFactory) {
.success(function(data) {
angular.forEach(data, function(value, key) {
if(data[key].value === -1) {
data[key].value = "undisclosed";
angular.element(document.querySelector('#value')).css( "color", "#FF2100");
$scope.acquis = data;

But that doesn't change anything. I'm really not sure if I'm approaching this at the right angle. How can I achieve this?

Answer Source

Perhaps you're overdoing it by trying to change the CSS in the directive. Couldn't you just use ng-style on your <h1> element like this?

<h1 id="value" class="value" ng-style="{ color: acqui.value=='undisclosed'? '#FF2100':'' }">{{acqui.value | shortNumber}}</h1>

This will check the value of acqui.value and use either #FF2100 if it's undisclosed or use no value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download