0

I want to change the text color of a row in an HTML table using jQuery if it founds this characther "-". The data is coming from a webservice and I'm using AngularJS but I don't know if I have to use directive to do this.

This is my angular expression:

<td>{{example.name}}</td>

and this is what I tried:

  $('.example.name').each(function() {
    if($(this).contains(-)) {
       $(this).css('color', 'red');
    }
  });

I put this code inside the controller that is bringing the data but it's not working, that's when I thought in directives.

So how can I achive this

3 Answers 3

2

You forgot to add " around - making it an operator and a Syntax Error. Change it to:

if ($(this).contains("-")) {
//-------------------^-^

The only place you can use without " is:

if ($(".some-class p:contains(-)")) {

Sorry I am not sure about the angular way! :(

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

1 Comment

Don't worry, everything helps. Thanks for your time ;)
2

You could use ng-class/ng-style directive to implement the same thing in angular way. ng-class is the preferable way to it.

HTML

<td ng-class="{red: doHighlight(exmaple.name)}" >
  ...content...
</td>

CSS

.red {
  color: red;
}

Controller

$scope.doHighlight = function(name){
   return name.contains('-');
}

6 Comments

Using the templating engine is probably the way to go.
I was just saying your answer is probably better than mine. Using Angular instead of jQuery. Keeping styling and layout in the template just seems cleaner.
@YourFriendKen yes..make use of inbuilt directive rather than going for jQuery
Thank's to both @YourFriendKen I was hoping to do this the "angular" way
@PankajParkar Me again, I was trying something like this: ng-style="{$('p:contains('-')').css('color','red')}" but not getting any result and I don't understand why. Also the solution you gave only works for example.name expression right? If I want to evaluate for any row in the table should be something like Ken said $("td:contains(-)").css("color","red"); no?
|
1
$("td:contains(-)").css("color","red");

Did you try using the jQuery selector :contains()?

https://api.jquery.com/contains-selector/

You may also want to add a class to the <td> elements that you want to query.

<td class="example-name">{{example.name}}</td>

Then change the query:

$("td.example-name:contains(-)").css("color","red");

1 Comment

This will work, now I think this should go inside a directive right? Because if I put that line inside between a <script> tag is not working..

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.