What is the best way to make ng-style append to a pre-existing style?

I am facing an issue with my custom popover directive and another custom directive that uses it. I am attempting to use ng-style to adjust the width of the popover. Below is a code snippet from the directive's html template:

<div my-custom-popover ng-style="{'width': widthVar}">
    ...
</div>

What's intriguing is that my-custom-popover also has an applied ng-style. Here's a snippet from its html template:

<div ng-style="{display: (condition ? 'block' : 'none')}">
    ...
</div>

The dilemma arises when angular attempts to render my directive. Instead of intelligently adding my ng-style to the existing one, it simply concatenates them, leading to a parsing error. Ultimately, the browser interprets my markup as

ng-style={'width': widthVar} {display: (condition ? 'block' 'none')}
, which obviously is incorrect.

Is there a way to instruct angular to append my ng-style to the existing one rather than just concatenate them?

Answer №1

It is generally not recommended to use inline CSS styles because managing multiple instances of the same rule in different elements can be cumbersome and error-prone. Instead, consider importing a CSS file where changes can be made easily and consistently.

In light of this, I suggest using ng-class over ng-style in your directive to apply CSS rules based on specific classes.

For instance, you could replace

ng-style="{display: (condition ? 'block' : 'none')}"

with

ng-class="{'show-div': show, 'hide-div': !show}"

Then, create a CSS file and add the following rules:

.show-div{display:block;}
.hide-div{display:none;}

Answer №2

It appears that merging attributes is not currently possible, as discussed in this ongoing issue.

If you're looking for a solution, you may want to try out the workaround suggested for custom directives like this:

compile: function compile(tElement, tAttrs, transclude) {
  tAttrs.ngClass = tAttrs.ngClass.replace(/}\s*{/g, ', ');
  // ...
}

This workaround corrects instances like

{'width': widthVar} {display: (condition ? 'block' 'none')}
by replacing } { with , before compilation.

For further reference, check out dariocravero's fiddle.

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

Cross-origin request blocked on DELETE operation due to preflight failure

I've been grappling with this error for a while now. I'm currently developing an Angular app (version 1.6.1) and encountering issues when trying to call a delete method on the API, which is built in symfony 3. Initially, I faced a preflight erro ...

What is the difference between a CSS background image and a default background?

I am faced with a challenge concerning a div element that has both a background color and an image with a transparent background. My objective is to have the default background color of the div be white, while having a different color as the background fo ...

Should you construct a fresh element using JavaScript, or opt to reveal a concealed one using CSS?

What are the benefits of using the following approach: var target = document.getElementById( "target" ); var newElement = document.createElement( "div" ); $( target ).after( newElement ); compared to just hiding the newElement div with CSS and showing ...

Numerous elements positioned absolutely are overlapping

I am working on a website with a unique slide layout design. I am currently focusing on two specific slides: https://i.stack.imgur.com/xngF4.png and https://i.stack.imgur.com/W19tJ.png My goal is to include a button on each individual slide, similar to th ...

Tips for aligning the dropdown menu to start from the border of the menu bar instead of displaying directly below the text

I have designed a menu-header section for my website, inspired by this image. I created a fiddle to showcase it. However, I am facing an issue where the dropdown elements for "PROGRAMS" and "WORLD OF NORTHMAN" should start from the border of the header ins ...

Tips for organizing the data you have collected from the table

After successfully printing all the data from my database, I am facing a challenge in designing my data effectively. The table I am working with is called post_tbl and it has columns named post_id, post_message, and post_date. This is the query I am usin ...

Indent the text within a span element that is displayed as an inline block

I am in search of a solution using only CSS for the following issue. Take into account the HTML below: <p> <span>Some text</span> <span>Some text</span> </p> Both <span> elements are set as inline-block. ...

How to Adjust the Padding of Tree Row in GWT?

Have you ever seen a GWT tree before? It sort of resembles the following structure: <div class="gwt-Tree"> <div style="padding-top: 3px; padding-right: 3px; padding-bottom: 3px; margin-left: 0px; padding-left: ...

The initial item in the Materializecss slider is failing to display

Currently, I am attempting to implement materialize slider with skrollr. The setup is functional; however, only the first item of the slider is set to opacity: 0 initially. https://i.stack.imgur.com/urSww.jpg After a brief delay, the second item becomes ...

Table featuring identical submit buttons in each row: initial submit button is nonfunctional (potential issue with multiple identical IDs)

My table displays product files, with the option to add notes. If a note is added, it shows in a row. If not, a text area field with a submit button appears instead. Everything seems to be working well, except for the first row without a note. After addin ...

The Safari browser is having trouble rendering the website's CSS and HTML properly

Check out this example of how the website should look on Chrome for Android: https://i.stack.imgur.com/RzUSp.jpg And here is an example from Safari on iPad Mini 2: https://i.stack.imgur.com/PAj2i.jpg The Safari version doesn't display the proper fon ...

Activate the timepicker in Bootstrap when the user clicks on the input field

Struggling to implement a timepicker feature? Look no further than this resource. After adding the necessary js and css to your project, you may encounter issues with the popup not appearing when clicked. The code provided offers a TextBox control with s ...

The inner HTML functionality in Angular 2 seems to be malfunctioning when dealing with HTML tags

I am facing an issue with an array that includes displayName with HTML tags: this.topicsList = [ {id: "173", name: "Discussion1", displayName: "Discussion1", status: 1}, {id: "174", name: "discussion123", displayName: "discussion123", status: 1}, {id: "19 ...

Utilizing jQuery's POST Method to Fetch JSON Data on a Website

I've developed a Java REST API and now I want to retrieve JSON data on my website (which is built using HTML & CSS) by utilizing jQuery. The method to be used is POST, and here is the structure of my JSON: { "sessionID" : "25574", "interactiv ...

The PHP form in an HTML file fails to function properly if multiple forms are included

When working with multiple forms in a PHP file that are called using the 'include' command, I encountered an issue where placing the include command before the forms on the HTML page made it work. However, I needed to call the include command bel ...

Utilize a fresh function in Angular to retrieve and store data from a URL into a variable

Currently, I am attempting to utilize Angular in order to retrieve data from a link upon clicking a button. As a newcomer to Angular with only 2 days experience, my knowledge is quite limited. What I aim to achieve is triggering the loading of JSON data w ...

Pattern to filter out numeric values from a collection

I want to apply a regex pattern to the <input> form element. The pattern should specify a range of numbers that are not permitted as input. For example, let's say I have a list of numbers like {1,4,10}, and any number other than these should be a ...

ngCordova camera functions properly on emulator, but encounters issues on actual devices

I am currently developing an app using Ionic for my Course Conclusion, and I am facing an issue with the ngCordova Camera Plugin. The deadline is approaching fast as I only have 2 weeks left to complete this project. While testing the app on the emulator, ...

Using Angular's built-in dependency injection with the $resource factory allows for

Question regarding Dependency Injection on factory resource: As far as I know, the following example is the recommended approach for injecting dependencies in Angular1: angular.module('myApp').factory('Resource', Resource); Resource. ...

Implementing MySQL in JavaScript code leads to various possibilities

I am working on a web application that requires retrieving values from a MySQL database. The process involves: PHP code generates an HTML page successfully. Clicking a button updates a cookie, which also works. Using the cookie in a MySQL query, which is ...