Is it possible to trigger a directive using a function and then access the generated style?

My directive is designed to randomly select a color and assign it to a new user as an avatar. The random color generation and directive functionality are working as expected, but I'm looking to expand the functionality further and need some assistance.

Currently, the directive activates as soon as the element enters the DOM. However, I would prefer it to activate when the user begins typing a name in the input field.

Additionally, when the addNewContact() function is called, the color is not being passed to the list of contacts. I'm hoping to find a way to extract the background color and pass it to the color field in my contacts.json file. Is this possible?

Below is the code for the directive:

 function randomBackgroundcolor() {
        return {
        restrict: 'EAC',
        replace: false,
        link: function (scope, element, attr) {

            //generate random color
            var color = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);

            //Add random background class to selected element
            element.css('background-color', color);
            //document.getElementById('newContact').style.backgroundColor = color;

        }
    };
 }

The HTML code:

    <md-dialog-content>
        <div class="md-dialog-content">
            <div class="mb-30 avatar-wrapper" layout="column" layout-align="center center">
                <span class="md-fab md-initials md-large mb-15" random-backgroundcolor>
                    {{contact.name | shortName}}{{contact.lastName | shortName}}
                </span>
            </div>
        </div>  
        <div class="" layout="column" layout-align="center center">
            <md-input-container class="md-icon-float" flex="100">
                <label>Name (required)</label>
                <input ng-model="contact.name" type="text" ng-required md-autofocus>
            </md-input-container>
            <md-input-container class="md-icon-float" flex="100">
                <label>Last Name (required)</label>
                <input ng-model="contact.lastName" type="text" ng-required md-autofocus>
            </md-input-container>
        </div>
    </md-dialog-content>

Snippet of the Controller code for adding a new contact:

function addNewContact()
{
        Contacts.unshift($scope.contact);
        closeDialog();
}

You can view the complete code on this PLUNKR.

Thank you for your help!

Answer №1

Connect the scope using replace: false, Ensuring synchronization between the controller and directive by sharing the same scope object. Utilize the scope by adding a $watch on the contact.name property. Whenever there is a change in the name, update the contact.color accordingly.

function generateRandomBackgroundColor() {
  return {
    restrict: 'EAC',
    replace: false,
    scope: false,
    link: function(scope, element, attr) {
      var color = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
      scope.$watch('contact.name', function(val) { 
        if (val !== '') { 
          scope.contact.color = color;
        }
      });
    }
  };
}

html : Update the span element with ng-style to access the color from the object instead

<span class="md-fab md-initials md-large mb-15" ng-style='{"background-color":contact.color}' generate-random-background-color>

Feel free to reach out

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

Is there a way to retrieve and gather all data from various scopes and then access them collectively?

I attempted to scrape information from a website using Node.JS + Cheerio + Axios. I was able to retrieve all the necessary data, but encountered an issue with returning the data from different scopes in order to receive it. Currently, I can only obtain the ...

What is the best way to store a WAV Blob in MongoDB, fetch it accurately, and serve it using Node

While there are many resources available on saving binary files using the Mongoose Buffer SchemaType, most of them focus on image files. I have encountered difficulties in making it work with a WAV audio file. Currently, I am utilizing Recorder.js to stor ...

A function similar to setCell for modifying form fields in JqGrid

After searching through numerous answers from @Oleg, I couldn't find the solution I was looking for. I am dealing with a grid where I can edit inline in certain fields. Specifically, I am working with autocomplete functionality and when I select an it ...

Guide to importing a Kotlin/JS generated module into a separate npm-dependent project

I am interested in developing a JavaScript library using Kotlin Multiplatform (such as the project found here, which includes a websocket server and a JavaScript client). My goal is to build this library as an npm package and then import it into my Vue pro ...

Integrate a fresh component and include a hyperlink to the URL simultaneously

Seeking to create a system where clicking an item in the navbar loads a new component on the screen, I am faced with the challenge of maintaining state while also updating the URL. Allow me to provide more details: Below is my current navbar code snippet: ...

Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some example ...

What is the best method to make a hyperlink within an IFrame open in a new window?

Let me share the code I've been working on: <!DOCTYPE html> <html> <head> <base target="_blank"> </head> <body> <div style="border: 2px solid #D5CC5A; overflow: hidden; margin: 15px auto; max-width: 800px; ...

Optimizing CSS With jQuery During Browser Resize

I am currently facing an issue with recalculating the height of the li element during window resizing or scrolling. Strangely, on page load, the height is no longer being re-calculated and set to the ul's child height. Here is the code I have written ...

Executing Node.js child processes: streaming stdout to console as it happens and running the processes one after the other

Details node: v9.4.0 I am looking for a solution to execute external commands sequentially while monitoring the stdout in real-time. The code snippet below demonstrates my attempt to retrieve all test cases from ./test/ and then running them one after ...

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

Angular: Built-in solution for managing unhandled HTTP errors

I have implemented a default handler for handling http errors in my angularjs app as shown below: myapp.config([ '$httpProvider', function($httpProvider) { $httpProvider.responseInterceptors.push('errorInterceptor') }]) The errorI ...

An error occurred when attempting to hide or show a jQuery loading animation

Here is the HTML code I am using: <div id="success_message" style="display:none"> <p>Good job!</p> </div> <div id="my-form"> <form> <input>....... (lots of inputs) <input id="my-btn" ...

encountered empty values when retrieving static paths

I need to retrieve the values of slug and tags in my params. It's important to note that tags is not an array, but just a string. export async function getStaticPaths() { const chapters = await client.fetch( `*[_type == "chapters" & ...

Why does the content not appear again when switching between tabs?

Hello! I'm facing an issue with toggling between two sets of content on my page. Initially, the correct content shows up, but when I switch tabs, the new content doesn't appear. Furthermore, if I click back to the first tab, that content disappea ...

What causes the appearance of a nested URL like '/auth/auth/ ' when the original URL does not exist?

While following a tutorial, I encountered an issue where if the URL is not included in the routes.ts file, it redirects to a nested /auth/auth/...../login/ instead of redirecting to localhost:3000/auth/login middleware.ts import authConfig from "./au ...

Is it possible to include if else logic code within a catch statement?

There's a nagging feeling within me that having logic code within a catch statement is not the right approach. For example, my catch block currently looks like this: try{ // do some stuff that throws some unexpected errors } ...

Extract the <img> element from the Angular model property

I'm currently leveraging Angular to display some HTML content: <p class="description" ng-model="listing.Description"></p> When the content is rendered, it includes images within the text, which is acceptable. However, now I aim to ident ...

ES6 allows for the retrieval of method data within an object

My goal is to improve the organization of my code by creating a config file where I can use the same method to set values. This is just a demonstration, so please keep that in mind. I'm wondering if there's a way to call a function based on wheth ...

Creating a single factory that consolidates multiple return statements

Exploring the ins and outs of AngularJS, I find myself eager to learn how to effectively combine two factory modules. Specifically, I am interested in merging the following two: // Factory Module One services.factory('UserService', function ($re ...

Relaunch node.js in pm2 after a crash

Based on this post, it seems that pm2 is supposed to automatically restart crashed applications. However, when my application crashes, nothing happens and the process no longer appears in the pm2 list. Do I need to enable an 'auto restart' featu ...