The use of Angular's ngClass directive does not work within the link function

I have a straightforward directive that renders an element, and this is the template:

<div class="nav-item"></div>

The .nav-item class looks like this:

.nav-item {
  height: 50;
}

Here's the directive in action:

angular.module('myapp')
.directive('navItem', ['info',
  function(info) {
    return {
      scope: {
        position: '@'
      },
      link: function(scope, element) {
        function _addData() {
          var rect = element.get(0).getBoundingClientRect();
          info.addData(scope.position, rect);
        }

        _addData();
      },
      templateUrl: 'tmpl.html'
    };
  }]
);

Everything works fine when the link function calls the _addData method, and the correct attributes are registered in a custom factory. However, the issue arises when I change the class attribute in the template to ngClass. If I use this syntax in tmpl:

<div data-ng-class="{'nav-item': true}"></div>

When _addData calls getBoundingClientRect, it erroneously returns a height of 1 instead of 50. It appears that the ngClass is not applied to the element when the link function processes it. How can I ensure that the correct element position is retrieved? I even tried including a postLink function in the directive to check the same, but it didn't solve the issue...

Answer №1

After doing some research and understanding about priority and terminal directive attributes, I was able to solve the problem. The issue was that ngClass was not executing before my link function because ngClass uses $watch in attribute, causing the digest process to execute ngclass in last order. To fix this, I simply used addClass in the link function instead of using ngClass:

Here is the template:

<div></div>

And here is the directive:

angular.module('myapp')
.directive('navItem', ['info',
  function(info) {
    return {
      scope: {
        position: '@'
      },
      link: function(scope, element) {
        function _addData() {
          var rect = element.get(0).getBoundingClientRect();
          info.addData(scope.position, rect);
        }
        element.children().eq(0).addClass('nav-item');
        _addData();
      },
      templateUrl: 'tmpl.html'
    };
  }]
);

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

In Node.js, when accessing a Firebase snapshot, it may return a

Currently, I am utilizing Firebase functions to execute the code for my Flutter application. This code is responsible for sending push notifications to my app. However, I am encountering an issue where I receive a null value at snap.val(). Take a look at h ...

Encountering the error 'Cannot read property 'length' of undefined' while attempting to fetch data from a URL using node.js

While attempting to create a Discord-Bot capable of looking up definitions on urbandictionary, I encountered an error after trying to fetch the json from their api. const args = Array.prototype.slice.call(commandArgs); if (!args.length) { return m ...

An approach to transferring the ID of a multiple dropdown within the $.each function

function filterFields(classname, value, chkClass) { var checkedfields = []; $.each($("."+classname+" option:selected"), function(){ checkedfields.push($(this).val()); }); $('#'+chkClass+'Filters').val(ch ...

When using next.js, a warning may be encountered that states: "A value of NaN was received for the `children` attribute. To resolve this, ensure the value is cast as

I am currently tackling my first Next.js project and have created a file called myCart.js. Below is the code snippet: function orderCard(arr1) { //Code here... } let noRefresh; function makeGetRequest() { //Code here... } export default makeGetReques ...

Padding in Bootstrap 4 columns in a vertical alignment when breaking the layout

I created a customized form-group to accommodate both large and small screens. The structure looks like this: <div class="form-group row"> @Html.LabelFor(model => model.ValidFrom, "Valid from", htmlAttributes: new { @class = "col-lg-3 ...

After diligently following every step on OneCheckout and getting no response when placing an order, I decided to upgrade my Magento version from 1.6.1.0 to 1.8

After upgrading the Magento version from 1.6.1.0 to 1.8.0, everything seems to be working smoothly. However, customers are facing an issue during checkout where they can't actually place their order. Despite following all the steps correctly, when t ...

How to vertically center a div using CSS

I need assistance center aligning #container with the following code: <div id="container"> <p>new</p> </div> The CSS provided is as follows- #container { position:relative; width:100%; background:red; padding:10px; ...

Components in Angular modules that are loaded lazily with identical names

I have developed an Angular application with multiple lazy-loaded modules. Each of these modules contains different components that are conceptually similar but vary in content. For example, each module may have its own "home" component. Is it advisable t ...

Applying Border Radius to JavaFX Components for a Unique Background Effect

When I apply the CSS properties -fx-border-radius and -fx-border-width to a basic GridPane, the background in the corner does not get "cut off". The following is the CSS code being used: .payload { -fx-hgap: 20px; -fx-padding: 40px; -fx-back ...

What is the best way to incorporate personalized events into an array using JavaScript?

Imagine we have an array called var arr = [1, 2, 3]. I am looking for a way to create a method that can observe any changes made to this array. The idea is something similar to the following: arr.on('change', function () { // perform some ac ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

"Encountering a problem with a missing object in jQuery when referencing

I'm encountering an issue with jQuery's $(this) object that's causing me to lose track of the this element in my code: $('.star').click(function (){ var id = $(this).parent().attr('id').split('rating')[ ...

Learning to transform EST time data into local time within JavaScript utilizing moment.js and Date objects

The recorded date and time is "03/19/2020 13:15:00" in Eastern Standard Time (EST). When attempting to convert it to the local timezone, I have tried various methods, such as using moment.js to change the format from 'MM/DD/YYYY HH:mm:ss' to UT ...

Passing large arrays of data between pages in PHP

I'm facing a challenge where I need to pass large arrays of data between pages. Here's the situation: Users input their Gmail login details in a form, which is then sent to an AJAX page for authentication and contact retrieval. If the login fail ...

Using React Hooks to render radio buttons within a map iteration

My code contains a nested map function where I try to retrieve values from radio buttons. However, the issue is that it selects all radio buttons in a row instead of just one. Below is the snippet of my code: <TableHead> <TableRow> ...

Show information according to the selection made in the dropdown menu

Greetings! I am currently developing a web app using MVC .NET (C#) that includes a registration page for two types of users, type 1 and type 2. In the form, there is a dropdown list where users can select their type. When selecting type 2, I would like t ...

Updating a nested object in MongoDB using Mongoose and calling the markModified method

Regrettably, I am lacking a suitable record to carry out a test on this. Furthermore, I have been unable to locate any information related to this particular issue. Let's consider a scenario where I have a document structured as shown below: { ema ...

Rating of displaying an undefined value (NaN)

I'm having issues with creating a currency conversion calculator, as the result is showing as NaN. Can anyone offer assistance? I've tried multiple solutions but have been unable to resolve it. Check out the following JavaScript code snippet: c ...

Utilizing PHP, Javascript, and jQuery in mobile technology gadgets

Can anyone recommend mobile technology products that have been developed using PHP, Javascript, and jQuery? What are the newest mobile products available on the market that have been built using these languages? Do popular devices like iPhone, BlackBerry ...

What could be the reason for the absence of the back button?

Having trouble understanding why the back button isn't showing up when I navigate to an <ion-view> app root state template: <ion-side-menus> <ion-side-menu side="left"> <div class="list"> <!-- ... --> & ...