Modifying text color on-the-fly with Angular JS directives

I'm having trouble with my directive, here is the code I'm using:

//profile colour directive
app.directive('profileColour', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var imageDiv = scope.$eval(attrs['profileColour']).imageId;
            var colour = scope.$eval(attrs['profileColour']).colour;
            var divName = '#name' + imageDiv;
            //$(divName).addClass("purpleText");
            $(divName).addClass("purpleText");
        }
    };
});

Here is the HTML snippet:

<table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th class="col-xs-2">
                            <span></span>
                        </th>
                        <th class="col-xs-8" ng-click="sort('firstName')">
                            <span class="glyphicon sort-icon" ng-show="sortKey=='firstName'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
                        </th>
                        <th class="col-xs-2">
                            <span></span>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-click="showModal($event, user.emailAddress)" change-image="{imageId: {{$index}}, colour: 'blue'}" dir-paginate="user in users|orderBy:sortKey:reverse|filter:search|itemsPerPage:5">
                        <td>
                            <img class="round" src={{user.profileImageUrl}} width="50" height="50"></img>
                        </td>
                        <td>
                            <div style="padding-top:1em"><span profile-colour="{imageId: {{$index}}, colour: 'blue'}" id='name{{$index}}'>{{user.firstName}}</span>
                                <br>{{user.lastName}}
                                <br>{{user.profession}}</div>
                        </td>
                        <td>
                            <div style="padding-top:1em">
                                <img id={{$index}} src="images/arrow-right-purple.png" width="50" height="50"></div>
                        </td>
                    </tr>
                </tbody>
            </table>

I'm trying to dynamically change the color of the span like this:

> <span profile-colour="{imageId: {{$index}}, colour: 'blue'}"
> id='name{{$index}}'>{{user.firstName}}</span>

I've defined the CSS for purple text as follows:

/*purple text */

.purpleText {
    color: #6c58bF;
    font-weight: 900;
    text-transform: uppercase;
    font-style: bolder;
}

But so far, it's not working. Any suggestions on how to make it work? Thank you!

Answer №1

When comprehending correctly, if the desired dynamic color option is stored in user.profileColour, you can implement something similar to this example:

<span  ng-class="{ 'purpleText' : user.profileColour === 'purple';  'greenText' : user.profileColour === 'green'}"> 

And so forth.

You have the option to generalize this into a function where you input user.profileColour and receive the corresponding class, based on where you want the logic (if converted into a function, it could all reside in the controller). For instance -

<span ng-class="setColor(user.profileColour)" >

and within the controller

$scope.setColor = function(color) {
  //assuming profileColour is purple this would return "purpleText"
  return color + "Text";
}

This assumes that all the profileColours are strings.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for securely saving a collection of objects in a cookie with json.stringify?

I'm encountering an issue while attempting to save an array of objects in a cookie using JSON.stringify. When I try to parse the cookie and add a new object to the array before stringifying it again, I receive an error stating that comments.push is no ...

Issue with __doPostBack method failing to render on subsequent postback

I'm encountering a peculiar issue. After using GetPostBackEventRefence to trigger a Postback, it initially works fine. However, after the first postback, the .NET function fails to render... any suggestions? This is what seems to be missing after th ...

Can we display a new post without refreshing the page in CodeIgniter?

Welcome everyone, I am currently working with Codeigniter 3.0.3. In my project, there's a feature to share posts using JSON jQuery data. I've noticed on many websites that when someone publishes a new post, it shows up on the same page without r ...

Is it possible to stack CSS pseudo-elements?

What is the most efficient way to create nested square-elements with minimal markup? I am aware that :after/:before cannot be stacked multiple times on the same element, so what would be the best way to achieve a structure like this? I am also facing chal ...

Odd behavior in Google Chrome when PHP includes JavaScript code

When working with my application built on Zend Framework, I have a layout.phtml file that contains the <head> section with some javascripts included using the following method: <head> // Some code <?php include('template/javascript ...

Mongoose - Error: Method 'findOne' is not callable

Having trouble integrating Facebook login with passport? Check out the error message below: TypeError: Cannot call method 'findOne' of undefined at Strategy._verify I made sure to include models.js in my app.js and passed it into the passport m ...

Arrange all the items in the list to be aligned on a single

Here is the code and styles I have in my project: I want to align the texts and span style. My default code looks like this: body { direction: rtl; } div { position: absolute; top: 30px; right: -100px; height: 300px; overflow-y: scroll; ba ...

Running sum queries on string objects in MongoDB with Node.js proved to be a challenging task

My MongoDB database contains documents with this structure: { "_id" : ObjectId("599ccc896f16e74a3e26f1a9"), "timestamp" : ISODate("2017-08-22T17:14:59.000Z"), "header" : { "uniq_id" : "9951503422099.16801274", ...

Links implemented with Bootstrap not functioning properly

I am currently working on a project using asp.net, and within my HTML markup I have the following code: <div class="col-md-4"> <div class="col-md-6"> <a href="#">1</a> </div> ...

Is it possible to use jQuery to add a CSS style and execute a function simultaneously

I need help with adding a CSS file to the current HTML page using jQuery. Here is what I have: var css = jQuery("<link>"); css.attr({ rel: "stylesheet", type: "text/css", href: "http://domain.com/chron/css/jquery.gritter.c ...

When loading JSON data dynamically into a D3 network visualization, the links may not be immediately visible

In my possession is a json file containing nodes and links defined with source and target attributes. { "links":[ {"_id": "5a4b2866235fa755b6576903", "target": 6746, "source": 2169}, {"_id": "5a4b2866235fa755b65768e3", "target": 67 ...

How to Handle Errors When Retrieving an AWS S3 Object Stream in Node.js

I am currently working on developing an Express server that will send items from a S3 bucket to the client using Node.js and Express. I came across the following code snippet in the AWS documentation. var s3 = new AWS.S3({apiVersion: '2006-03-01&apo ...

The vertices in Three.js BufferGeometry refuse to update

As I strive to connect grid tiles with real elevation data from IndexedDB, I encounter a challenge due to the imperfect data resolution on the STRM elevation causing discrepancies at the edges between the tiles. To address this issue, my goal is to average ...

Improving a Vue.js notification component with data retrieved from a fetch request result

Struggling with updating the content inside a vuetify v-alert. There's an issue when trying to update Vue component properties within the sessionID.then() block after logging into a system and receiving a session id. Vue.component('query-status ...

Unable to stack a text element on top of another element with CSS

I am a novice looking to delve into the world of programming. Currently, I am immersing myself in learning HTML and CSS while embarking on my inaugural project. The task at hand involves creating a simple homepage for a local game store with the objective ...

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

How can you automatically show the current time upon entering a page using React Native?

Is there a way to automatically display the current time when a user enters the page? I currently have code that only shows the current time when the TouchableOpacity is pressed, but I want it to update automatically as soon as the user arrives on the Ne ...

assigning a numerical value to a variable

Is there a way to create a function for a text box that only allows users to input numbers? I want an alert message to pop up if someone enters anything other than a number. The alert should say "must add a number" or something similar. And the catch is, w ...

The loader function for createBrowserRouter in React Router is causing an infinite loop

I have encountered an issue with implementing loader functions on my browser router. The functions trigger an API call that updates a context state value. However, updating the state is causing the loader function to run again, resulting in an infinite loo ...

unable to access stored locations in XML file using JavaScript

I am attempting to retrieve a saved location from a database using JavaScript to read from an XML file. My goal is to add markers to a map based on these saved locations. Below is the XML code, can you identify any issues with my method of reading the XML? ...