combine ngClass properties if substitution is true

My directive includes replace: true in the definition.

<my-custom-tag>
</my-custom-tag>

This is the template for the directive:

<div data-ng-class="{'class1': condition1, 'class2': condition2}">
</div>

When using my directive like this, it generates an error:

<my-custom-tag data-ng-class="{'class3': condition3}"></my-custom-tag>

The error occurs because the template already defines a data-ng-class attribute, resulting in the following HTML:

<div data-ng-class="{'class3': condition3} {'class1': condition1, 'class2': condition2}"></div>

Is there a way to merge these objects to avoid syntax errors during compilation?

Check out the Plunkr example, view the browser console for error messages, and inspect the element to examine the data-ng-class attribute.

Answer №1

There was a discussion thread addressing this issue.

To address the problem, you can utilize the compile function to make modifications before the link function is activated. Check out this Plunkr example.

angular.module('directive', []).directive('myCustomTag', function() {
  return {
    template: "<div data-ng-class=\"{'foo': whenFoo()}\">My Custom Tag</div>",
    restrict: 'E',
    replace: true,
    compile: function compile(tElement, tAttrs) {

      tAttrs.ngClass = tAttrs.ngClass.replace(/}\s*{/g, ', ');

      return function (scope, iElement, iAttrs) {
        scope.whenFoo = function() {
          return true;
        };

      };
    }
  };
});

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

Modifying the chart width in Chart.js: A step-by-step guide

After creating a chart using Chart Js, I encountered an issue where the chart did not fit within the specified width. Adjusting the attributes of canvas proved to be ineffective, specifically with regards to the width attribute. Despite changing the value, ...

Is it feasible to access a variable outside the scope of a function if it is initially created within the scope of another function that returns a function using that same variable?

function creatPrintNumFunction() { var num= 12; return function printNum() { console.log(num); } } var printer = creatPrintNumFunction(); printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside t ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Utilizing AngularJS for seamlessly closing Bootstrap Modal Popup

Having recently delved into AngularJS, I am seeking assistance with a particular issue; In my AngularJS (v 1.6) application, there is a Bootstrap modal window for user login. Once the user successfully logs in, I wish for Angular to automatically close the ...

What is the correct way to add a library to webpack configuration?

Currently, I am working with Rails 6 and webpack in my project. I am interested in integrating the library jquery-textcomplete, but I am unsure about how to properly include it in the application.js file. Here are the steps I have taken so far: I instal ...

Incorporating Images in AngularJS based on Boolean Values Retrieved from Model Database

I have a requirement to display images in a table based on true and false values from the 'user' collection. How can I achieve this functionality? Here is the code snippet: <div class="col-sm-12"> <div class="info-box"> <d ...

The page is undergoing a refresh and the query will not be executed - Ajax and PHP working together

function submitComment(ele) { event.preventDefault(); var username = "<?php echo $current_user; ?>"; var user_id = "<?php echo $current_user_id; ?>"; var post_id = $(ele).data('id'); var comments = $(ele).parent(".comment-se ...

Sending arguments enclosed in double quotation marks

Having an issue while trying to pass a variable with the character ", especially when dealing with "Big Bang". <?php echo $aux; //Hi! "Text" Text2'Text3 ?> //mysql_real_escape_string($aux); addslashes($aux); //output Hi! \"Big Bang&bso ...

express-validator, no validation errors have been found so far

How can I verify if a given string is in the format of an email address? Here's a snippet of code that attempts to do so: req.checkBody('email', 'Invalid email address').isEmail(); var validationErrors = req.validationErrors(); i ...

Access the contents of MUI Modal (Dialog) even when it's closed

I'm currently working on an app using Material-ui and firebase authentication. My goal is to integrate firebaseui's authentication within a MUI Dialog component. The issue I've encountered is that in order for the authentication component t ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

Retrieve the decimal separator and other locale details from the $locale service

After reviewing the angular $locale documentation, I noticed that it only provides an id (in the form of languageId-countryId). It would be helpful to have access to more specific information such as the decimal separator character. Is there a way to retri ...

Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

Does the react key have scope limited to the local environment or does it have

After reading this intriguing article discussing the use of the index as a react key, I began to ponder. Imagine having two distinct lists: <List1> <el key="1" /> <el key="2" /> </List1> <List2> <other-el key="1" / ...

Unraveling the mysteries of the Bootstrap carousel script

Hi everyone, I'm a newcomer to the world of JS and jQuery. Recently, while examining the code in carousel.js, I stumbled upon this particular line: this.cycle(true) The cycle function is structured like this: Carousel.prototype.cycle = function ...

How to use mousedown event in Three.js to create line drawings

I've tried multiple approaches to achieve this effect. I'm looking to draw a line on mouse down event, and despite researching various resources, I haven't been able to come up with a solution. Currently, I'm utilizing the RayCaster met ...

Tips for eliminating repeated values in a textbox

<script> $("#filter").on("shown.bs.popover",function(){ $(".popover-content input[type=checkbox]").on("click",function(){ if(this.checked) { this.setAttribute("checked","checked"); } else { ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

Try implementing Underscore/Lodash to organize an object by values and convert it into an array of pairs that can be utilized with AngularJS ng

My goal is to showcase the details from the given object on the user interface using Angular's ng-repeat. It is essential for me to arrange the key/value pairs based on their values and exhibit them in sequential order in an array from highest to lowe ...

Preventing users from inputting the symbols "+" or "-" in a React JS input field

Essentially, the input field should only accept values between 1 and 999 Input Field : <input type="number" value={value} onChange={this.props.onViltMaxUserChange} min="0" max="999" /> onChange : onViltMaxUserChange = _.throttle(e = ...