What causes the ng-class directive to be executed subsequent to my custom directives?

For the example I am referring to, please visit: http://plnkr.co/edit/oYvwHnAIvFb4rUqqwsz3?p=preview

Hello, I am facing a situation where Angular seems to be compiling my code in a way that I do not fully understand. I have an outer directive that is iterating over an array and creating a new directive for each item in the array. Each of these inner directives is wrapped within a div with an ng-class attached to it.

The problem arises when I try to apply the ng-class to the wrapping div before the link function of the nested directives is executed. Currently, all controller and link functions of the nested directives are compiled before any ng-class functions are called on the wrapping div. You can observe this behavior in the provided plnkr example (check the console log for the order of execution). The desired print order should be as follows:

adding class to inner directive 1
Inner - Controller undefined
Inner - Link 1
adding class to inner directive 2
Inner - Controller undefined
Inner - Link 2
Inner - Controller undefined
...

I would appreciate any assistance in understanding this issue or achieving the desired compilation order.

relevant code: html

<div bn-outer>
      <div ng-repeat="a in arr">
        <div  ng-class="classFunction(a)">
          <span bn-inner ng-model="model" ng-init="model=a">

            directive: {{a}}

          </span>  
        </div>

      </div>
    </div>

angular

    // Create an application module for our demo.
    var app = angular.module( "Demo", [] );

    app.directive(
        "bnOuter",
        function() {
            function Controller( $scope ) {
                console.log( "Outer - Controller" );
                $scope.arr = [1,2,3,4,5,6];
                $scope.classFunction = function(int){
                  console.log("adding class to inner directive ", int);
                };
            }
            function link( $scope, element, attributes, controller ) {
                console.log( "Outer - Link" );
            }
            // Return directive configuration.
            return({
                controller: Controller,
                link: link
            });
        }
    );

    app.directive(
        "bnInner",
        function() {
            function Controller( $scope ) {
                console.log( "Inner - Controller", $scope.model );
            }
            function link( $scope, element, attributes, controller ) {
                console.log( "Inner - Link", $scope.model );
            }
            // Return directive configuration.
            return({
                controller: Controller,
                link: link
            });
        }
    );

Thank you!

Answer №1

If you're looking for more information on this topic, I highly recommend checking out the following resources:

Another great read can be found at:

It seems like focusing on the 'pre-link' function is key to understanding this concept.

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

Do I require two bot logins for discord.js?

Working on my discord bot, I've been trying to incorporate a script from index.js. Should I also include bot.login at the end of cmdFunctions.js? Here is the content of index.js: const Discord = require('discord.js'); const bot = new Discor ...

The prop type `cellHeight` provided to `GridList` in (Material-ui / React) is invalid

warning.js:33 Warning: The prop type for cellHeight in the GridList component is invalid. I encountered this error message, despite the property functioning correctly. Is there a way to resolve this issue? If you're interested, check out the documen ...

How can I create a hover effect animation in React?

I am looking to replicate the menu item underline animation demonstrated in this example. In jQuery, I would easily achieve this by obtaining the left position and width of a menu item, then using stop.animation on hover. Attempting this animation with R ...

Next.js directs API requests to the root URL

I'm currently working with an API handler pages/api/[slug]/[uid].ts My goal is to redirect the requests to the main root of my application, specifically: http://localhost:3000/[slug]/[uid] What steps do I need to take in next.config in order to mak ...

Display a fancy slideshow that transitions to five new images when the last one is reached

Here is a screenshot of my issue: https://i.stack.imgur.com/duhzn.png Incorporating Bootstrap 3 and FancyBox, I am facing an issue with displaying images in rows. When I reach the last image, clicking on the right arrow should result in sliding to anothe ...

What is the best way to retrieve form values on the server in nextJs?

I'm facing an issue with passing form data to my API endpoint in nextJS. I have set up the form using Formik and Yup for validation. Oddly, when I check the console on the client side, I can see the user input values just fine, but on the server side, ...

Identify Safari browser and redirect visitors

Here is the script I am using to detect and redirect a page specifically when Safari is used: if(/safari/.test(navigator.userAgent.toLowerCase())) { window.location.href = "elsewhere.html" } Currently, it redirects in both Safari and Chrome. How can ...

Once the image is requested in HTML, three.js makes a subsequent request for the same image

This is a block of code. let image = new THREE.TextureLoader().load("http://odf9m3avc.bkt.clouddn.com/1493817789932.jpg") <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script> <img class='preLoad&apo ...

Creating an array from a collection of dataset Id values acquired from a div

The dataset Id is linked to the image. Suppose I have assigned different dataset Id values to a set of divs, how can I gather these values and create an array with them collectively? I attempted to loop through them as they all have the same class name, b ...

Retrieve an HTML document from a specified URL using JavaScript AJAX methods

var $ = require('jquery'); $.ajax({ type:"GET", dataType: 'html', url: 'http://www.google.com/', success: function(res){ console.log(res); } }); The error displaying in the console is: XMLHttpRequest cannot lo ...

Displaying both the label and store ID in Jquery autocomplete data

I have implemented jQuery UI autocomplete with an AJAX source on my input field. The goal is to display the label to the user, while storing the corresponding ID in the value behind the scenes without using a hidden field. I aim to achieve this by storing ...

Submitting an ASP.NET MVC form with jQuery and passing parameters

Having trouble passing the ThreadId parameter when submitting a form to my controller through jQuery Ajax. The code works fine, but for some reason, the ThreadId doesn't get passed using form.serialize(). Any suggestions on how to effectively pass par ...

What is the process for extracting HTML code from a URL in a web browser?

Is there a way to view HTML code in preview mode on a browser? similar to this example The output of the link should display as "{{ color.name }}" ...

Obtaining the URL of the Parent Page Using Javascript

I encountered a situation in which, when I open a modal window dialog from Page1.aspx, if a user attempts to directly open that dialog by copying the URL and pasting it into the browser, I want to prevent the modal window from opening. It should only open ...

Increase the count if the item is already in the shopping cart - React

Is there a way to avoid adding the same product to the basket multiple times and instead just increment a counter? How can I effectively keep track of each item's count? this.state = { description: '', commaSalesPrice: '', ...

Exporting an angular component as a module

I have successfully created a widget using Angular elements that works well in HTML. However, I am unsure of how to export it as a module for use in other Angular, React, Vue web applications. I want to be able to import import { acmaModule } from package- ...

What possible reasons could there be for my vue project failing to load the JavaScript file?

I encountered an issue with my login page and script.js file while setting up my project. Strangely, my Vue application is not loading the JavaScript file as expected. The console displays this error message: https://i.sstatic.net/QG0hL.png The error seem ...

Uploading Files with Ajax in Asp.Net Core

Hey there! I'm facing an issue while attempting to upload a file using ajax from the client side to the server side (asp.net core) controller as I keep getting a null value. Below are my HTML and JavaScript codes: <input type="file" id="myfile" ...

Is it possible to utilize PropTypes to indicate that a prop is of type Promise?

Using PropTypes can aid in debugging by providing warnings when expectations are not met. Additionally, they serve as a helpful tool to clearly express how a component should be used. If I have a component that requires a prop with a value that could pote ...

What steps can I take to avoid the replacement of a default user image in my Firebase 9 application?

I have been working on a chat application using React 18 and Firebase 9. One issue I encountered is with the Register form, specifically with an input field of type file for uploading the user's avatar. The avatar field in the form is not mandatory, ...