Send the parameter to the compile method within the directive

I am currently working on creating a generic field and utilizing a directive for it. In my HTML code, I have defined the following:

<div def-field="name"></div>
<div def-field="surname"></div>
<div def-field="children"></div>

These fields can be of two types: either a simple element (like the first two) or a list of elements (like the third one). The scope variable contains the definitions of all fields and their respective types. To handle this, I have developed the "def-field" directive:

app.directive("defField", function($compile, $parse, $http) {
  restrict: 'A', // only for attributes
  scope : true,

  return {
    restrict: 'A', // only for attributes
    scope : true,
    compile: function compile(tElement, tAttributes) {

      //I need to determine the type of field here.
      //If it is an array, special compiling code needs to be executed      
      if(fieldType === 'array') {
        //execute special code for compilation
      }

  }

  if(fieldType === 'array') {
    //return value for array type
    var returnValue = {pre : linkFunction};
  } else {
    //return value for normal type
    var returnValue = {
       pre : linkFunction,
       post: function(scope, element, attrs){
         $compile(element.parent())(scope);
       }
     };
   }
  return returnValue;
}

The challenge I am facing is that I need to access the fieldType from the scope variable within the compile function, where the scope variable is not accessible. Is there a way to overcome this issue?

Currently, I am passing the type as an attribute, but this approach is not ideal in the long run.

Answer №1

Having delved into some Angular material, I was able to uncover a solution. Unfortunately, in my application, the bulk of the business logic resided within controllers, which goes against style guidelines:

Angular 1 Style Guide by John Papa (business logic)

Angular 1 Style Guide by Todd Motto (business logic)

Consequently, I relocated my business logic to controllers and successfully retrieved the necessary data in a directive from a service. To illustrate this, I have put together a brief demonstration:

Link to Plunker

Explanation of code: Initially, I created a service to fetch the required data:

(function () {

"use strict";

angular.module("dirExampleApp").service("directiveService", ["$timeout", function ($timeout) {

        var self = this;

        self.getObjectData = function () {
            return $timeout(function () {

                var responseFromServer = {
                    firstName: {
                        value: "firstValue"
                    },
                    secondName: {
                        value: "secondValue"
                    },
                    thirdName: {
                        value: "thirdValue"
                    },
                    fourthName: {
                        value: "fourthValue"
                    }
                };
                self.content = responseFromServer;

            }, 300);
        };
    }]);
})();

Subsequently, I could inject this service and utilize it in my directive within either the compile, prelink, or postlink functions:

(function () {

"use strict";
angular.module("dirExampleApp").directive("dirExample", ["$log", "directiveService", function ($log, directiveService) {

        return {
            restrict: "A",
            template: "<h3>Directive example!</h3>",
            compile: function (tElem, tAttrs) {
                var fieldName = tAttrs.dirExample;

                $log.log('Compile function: Field with name: ' + fieldName +
                        ' and sevice provided the following data: ' +
                        directiveService.content[fieldName].value);
                return {
                    pre: function (scope, iElem, iAttrs) {
                        var fieldName = iAttrs.dirExample;
                        $log.log('Prelink function: Field with name: ' + fieldName +
                                ' and sevice provided the following data: ' +
                                directiveService.content[fieldName].value);
                    },
                    post: function (scope, iElem, iAttrs) {
                        var fieldName = iAttrs.dirExample;
                        $log.log('Postlink function: Field with name: ' + fieldName +
                                ' and sevice provided the following data: ' +
                                directiveService.content[fieldName].value);
                    }
                };
            }
        };

    }]);

})();

As a result, there is logging when the directives are instantiated. This logging illustrates that the essential data has been successfully fetched from the service in the compile, prelink, and postlink functions of the directive:

https://i.sstatic.net/Th8d7.jpg

Please note: I am uncertain whether it is permissible to use service, factory, or provider for the purpose of supplying data. I simply demonstrated how it can be achieved with service. Presumably, the process is similar with factory and provider.

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

When utilizing webpack in Angular 5, the :host selector does not get converted into a component entity

Initially, I set up Angular with webpack following the configuration in this guide, including configuring webpack sass-loader. Everything was working smoothly until I encountered an issue today: app.component.ts @Component({ selector: 'ng-app&ap ...

Is there a way to identify whether the image file is present in my specific situation?

I have a collection of images laid out as shown below image1.png image2.png image3.png image4.png … … image20.png secondImg1.png secondImg2.png secondImg3.png secondImg4.png secondImg5.png ……. …….. secondImg18.png My goal is to dynamically ...

Utilizing jQuery to implement a function on every individual row within a table

I have a collection of objects that requires applying a function to each item, along with logging the corresponding name and id. Below is the snippet of my code: var userJson = [ { id: 1, name: "Jon", age: 20 }, { ...

Tips on incorporating a dynamic variable value as a class name within a span tag

I am a beginner in the world of JavaScript. Below is the code snippet I am working with: result.push(`<span class="mark">${str.substring(h.startOffset, h.endOffset)}</span>`); Currently, I have a variable called var className = "dynamicvalue" ...

Remove any words that are not included in the specified list

Here is the code snippet to achieve the desired functionality: const { words } = require("../../json/words.json") const args = message.content.split(' ') const wordss = words.filter(m=> m.includes(args)) if(args > 1 || !wordss) { ...

The filtering feature for array and model selection in Angular's UI-Select appears to be malfunctioning

Below is a Json structure: $scope.people = [ { name: 'Niraj'}, { name: 'Shivam'}, { name: 'Arun'}, { name: 'Mohit'}] There's also a variable, var array = "Niraj,Shivam";. My goal is to filter out the names fro ...

Enable modification of form field once a personalized dynamic stamp has been applied

I currently have a functional custom dynamic stamp that includes multiple input fields prompting the user. My goal now is to integrate a form text field onto the stamp after it has been rendered. For example, if someone stamps everything except for the led ...

Struggling with implementing Bootstrap modal JavaScript in Rails 4, nothing seems to work!

This situation has been addressed in numerous posts, but despite my efforts to find a solution among them, I have yet to come across one that works for me. I am faced with the task of opening a modal that requires JavaScript modifications before being dis ...

Tips for creating a drawing grid with a table

I am currently working on a project where I need to create a canvas-like table with around 10,000 cells. The goal is to allow users to draw on this canvas by moving their mouse over it while holding down specific keys (e.g. ctrl for blue, shift for red). ...

How can I retrieve the chosen value from an AJAX combobox using JavaScript in an ASP.NET C# application?

How can I retrieve the selected value from an AJAX combobox item using JavaScript in ASP.NET C#? Below is the code snippet: <asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction()" AutoCompleteMode="SuggestAppend" CssCla ...

How to dynamically populate a Vue multiple select dropdown with v-for loop?

I have been attempting to implement multi-select questions in Vue using v-for. The Select menu and its options are populated via JSON data. Unfortunately, I am facing difficulty in retrieving the selected results as expected. Whenever I select an option ...

Trouble accessing Strapi CMS data on Next.js frontend using React.js

Currently, I am in the process of developing a website using Strapi as the CMS and Next.js(React) for the Frontend. The website features an image slider that includes an image, a headline, and a description. I am trying to retrieve these elements from my S ...

Issue with custom Javascript not executing in Internet Explorer versions 9 and 10

Initially, this script is found in the document's head section. <script> document.addEventListener("DOMContentLoaded", function () { var e, t = document.querySelectorAll("div.bounceInDown"); for (var n = 0, r = t.length; n & ...

Effective ways to enable users to upload files in a React Native app

Being in the process of developing a react native app, I am faced with the challenge of allowing users to easily upload files from their mobile devices (pdf, doc, etc). Unfortunately, my search for a suitable native component has proven fruitless. Can anyo ...

"Encountering an Error in Linq Query Due to Union Operator Usage

Integrating a WCF service into an AngularJS web application has presented a challenge. With two tables in the database, the goal is to join their records into a single record for display in the AngularJS application. When both tables have records, retrieva ...

Test success despite Cypress assertion failing

Conducting integration tests on an API. Encountering a scenario where one test passes while another fails despite having similar assertions. Feeling confused about the handling of async/promises in cypress. context("Login", () => { // This t ...

What is the best way to execute multiple functions in sequence and halt the process if any of them encounter an error?

I am working with multiple Javascript functions that manipulate the DOM and run ajax requests. My goal is to execute these functions sequentially, one after the other, and only proceed if none of them return false from their ajax request. If any function r ...

Determine the presence of a value within an array in mongodb

How can I determine if the current Meteor.user()._id exists in the "favoritedBy" array? If true, display "Your favorite", if false, display "Not your favorite". Here is an example document in MongoDB: { "_id" : "W5WwAZatorDEb6DNP", "createdBy" : "aT ...

Defining the active element in the menu using JavaScript

I need help with my navigation menu: <ul> <li id="active"><a href="/">Home</a></li> <li><a href="/about/">About Us</a></li> <li><a href="/services/">Our Services</a>< ...

Is there a more efficient method for writing my jQuery code that follows a step-by-step approach?

I have developed a step-by-step setup process that guides users through various sections. Instead of using separate pages for each step (like step1.php, step2.php, etc.), I have all the code contained in one page named setup.php. This is achieved by utiliz ...