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!