Is it Possible to Modify CSS Dynamically within an Angular Directive?

I am currently developing a directive for an input field of type text. My goal is to have the width of this field expand dynamically if the text exceeds the size of the input field. Below is the code snippet for my directive:

.directive('dynamicInput', function () {
    return {
        restrict: 'E',
        template: '<input type="text" style="display: inherit;" class="form-control" required />',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {


            console.log('ATTRS: ', attrs);
            console.log('ELEMENT: ', element);

            if(attrs.width){
                console.log('WiDTH: ', attrs);

            }

        }
    }
});

Check out the Plunker demo here:

Change Width Dynamically.

I am aware that it is possible to change the CSS class on the element object, but I am looking for a solution that dynamically adjusts the width as the text length increases within the input field. My question is: How can I update the CSS based on the text length with every 'onchange' event? Additionally, I want to achieve this within a directive, without relying on the parent scope where it is declared.

Answer №1

If you retrieve your input element, you have the flexibility to manipulate it using vanilla JavaScript or an Angular object element.

For example (using link function):

var inputElement = angular.element(element.children()[0]);

inputElement.on('keydown', function() {
   inputElement.attr('size', inputElement.val().length); 
});

While this may not achieve your exact desired outcome, it demonstrates the concept. With access to the element within the directive, implementing such logic is straightforward and self-contained.

See the modified Plunker here.

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

The site is visually appealing in Firefox, but has a few issues on Chrome

I've encountered a common issue where my website displays perfectly in Firefox but looks terrible in Dreamweaver and Chrome. To fix it, I made live CSS edits in Firefox then copied them to Dreamweaver resulting in a mess. Here's how it should lo ...

Troubleshooting the fluid container problem in Bootstrap 3

I am currently working on a website using Bootstrap 3 framework. I have a specific section where I need to have two fluid containers placed side by side, each with different background colors. One of these containers should also include a background image ...

Is there a way to conceal/remove the text displayed on the submit button?

I am facing an issue with a submit button in my PHP code. The button displays an integer value that is crucial for running a script, but I want to hide the value as it interferes with the design using CSS. I have attempted various solutions like removing t ...

Do you know of a more streamlined approach to formatting this SCSS code?

Currently working on a Saleor Site and diving into the world of Django and SASS for the first time. While crafting my own styling rules in SCSS files, I've noticed some repetitive code that could potentially be streamlined. It seems like there should ...

jQuery - Modify Turn.js to exclusively implement the page Peel effect

I am attempting to implement the peel effect from turn.js into my code, where hovering over the bottom right corner of the page causes it to peel slightly and appear as if it is bending upwards. I specifically want only the peel effect and not the entire ...

Applying onclick css changes to a specific duplicate div among several others?

Recently, I encountered a situation where I have multiple identical divs on a page. <div class="class" ng-click="example()"></div> With the use of Angular 1.6.4 and jQuery, these divs are styled with background color and border color. Now, w ...

Stretching background images on iOS mobile devices

My background is causing issues on iOS devices by stretching only when there is content added to a page like this. However, it loads correctly on empty pages like this. I have tried adding background-attachment:scroll instead of background-size: cover to ...

The performance of Ionic scroll is hindered by a slow response time coupled with a

I'm experiencing an issue where the page loads square by square when I scroll, which looks like this: https://i.sstatic.net/yHNLx.jpg Here is the code snippet: categoryList.html <ion-header-bar align-title="center" class="bar-stable"> < ...

Learn the method for switching between exclusive visibility using Bootstrap class toggles

I've set up a jQuery function that toggles the visibility of different divs when clicking on folder icons: $(document).ready(function() { $("#techfolder").click(function(){ $("#txt").toggleClass("d-none"); }); $("#persfolder").click(functio ...

Uploading files with AngularJS

Looking to implement image uploading in an AJAX manner, I found a helpful Article that guided me through the process. Here's what I've accomplished: In the Controller: $scope.uploadImage = function () { var result; var formdata = new F ...

Is it possible to create a basic textarea with minimal height-rows but fill 100% of the height?

Within my div, there is a textarea element that I am having trouble sizing correctly vertically. The container div is set to the right size (100%), but I need to give the textarea a minimum height or number of rows to enable scrolling if needed, while sti ...

What is the best way to create a fade effect when toggling the class "hover"?

I've searched and searched online, but haven't found a solution. I want a specific section of my webpage to gradually appear when I hover over it. Below is the CSS code I'm using: .status .admin { display: none; } .status.hover .adm ...

The alternative text for the oversized image exceeds the boundaries

After setting the width and height for an image, along with testing overflow:hidden, I've encountered an issue where the alt text for a broken image overflows the bounds of the image and the image size is lost. How can I contain the alt text within th ...

Is there a way to assign the value of a textfield to a session attribute in JSP prior to rendering?

Imagine I have the following code snippet: <html> <head> <script> function setSession() { var roll=document.getElementById("rollno").value; session.setAttribute("rollno", roll); } & ...

Connect Angular Material by chaining together md-select elements from arrays and array of form inputs

I am encountering a challenge with combining chains in Angular Material. I aim to transition from this linked solution on jsfiddle to using md-select and md-option in Material. How should it function? It's quite simple. Here's the scenario: Se ...

In JavaScript, when a condition is met, two strings are produced but only the last string is printed

My for loop with nested arrays is working fine, but it should display two strings and only shows the last one. for (i = 0; i < $scope.taskGroups.length; i++) { for (j = 0; j < $scope.taskGroups[i].tasks.length; j++) { ...

Cross-origin resource sharing (CORS) file uploading in AngularJS, compatible with Internet Explorer

I am looking for a simple and lightweight method to upload a small file to a REST API while utilizing CORS. I currently rely on the angular-file-upload plugin. Unfortunately, a problem arises with this plugin as it utilizes swf fallback for outdated brows ...

two adjacent elements filling the entire height of the window at 100% dimensions

Is there a way to place two elements side by side, with one of them (the textarea) always being 100% height of the window? I've looked at similar questions here but can't figure out how to make it work. Can you help me with this? html: <div ...

Having trouble displaying generic error messages with AngularJS and ng-messages?

Check out my HTML code: <script type="text/ng-template" id="my-custom-messages"> <div ng-message="required">This field is required</div> <div ng-message="minlength">This field is too short</div> </script> <form ...

Gradually blend the section of the picture with an image banner after 20 seconds

I have a background image that rotates every 20 seconds, fading in and out. The images consist of a logo at the top-left corner and a person image at the right side from top to bottom. However, I want only the person image to fade in and out while keeping ...