2

I'm confused, I have a jquery script that change the text color to red if it finds a negative number in an html table.

   console.log("reading Script");
    $('td:nth-child(3)').each(function() {
      var txt = $(this).text();

    if (txt.indexOf('-') > -1) {
       $(this).css("color", "red");
       console.log("True: " + txt);
    } else {
       $(this).css("color", "green");
       console.log("False: " + txt);
    }
});

This script works perfect in one example where I'm using "ng-repeat d in data" with this expression {{d.category}} but I have a second example that it's not working, I'm using the same script but the angular expression is differente bucause the JSON structurure that Im reading is different, ng-repeat="data in PostResponse.result" and my angular expression goes like this {{data.merchMetrics.category}} and here I'm getting all the values in green, even the negative numbers so I dont get it, because the first example is quite the same, the only thing that is different is the structure of the data.

Even the console log works different, in my first example logs something like this:

  • True: -4
  • False 10

This is ok but in the second example Im getting this in the console:

  • False: {{data.merchMetrics.category}}

So, any ideas?

1 Answer 1

4

You are using jQuery coding practices in an Angular app and this will cause you headaches - for once because those practices go against the Angular spirit, and also because you won't reap the benefits of Angular.

Most likely you have a timing problem where in your first case Angular has already substituted your template expressions with values and in the second case not. You shouldn't manipulate the DOM like this. One of the most important parts in Angular development is: you shouldn't parse data back from the DOM, ever.

You should use ng-class to do conditional formatting.

<td ng-class="{ positive: data.merchMetrics.category < 0, negative: data.merchMetrics.category >= 0}">{{data.merchMetrics.category}}</td>

and then define two CSS classes, positive and negative with font-colors of red and green respectively.

A bit more background why Angular should be used differently than jQuery can be found here among other resources:

Sign up to request clarification or add additional context in comments.

2 Comments

Great @JohannesJander Thank's for your time :)
Most likely in one case it works because the data is already there when the jQuery script runs, in the other case not yet (Javascript is asynchronous). You might need to read more about angular, you don't call the class, you load the data and Angular calculates the class based on the value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.