Revealing an Angular directive's functionality to a different module

Imagine having a module with a directive structured as follows (this is a rough, untested implementation) There are 3 fundamental requirements that need to be fulfilled:

  1. Set up configuration for the element display
  2. Add event listeners accessible by the base controller
  3. Create public methods that can be invoked by the base controller

angular.module("componentModule",[]) .directive("myComp",function(){

return{
    replace:true,
    template:'<h2>This is my component</h2>',
    scope:{config= "@"},
    link:function(scope,element,attr){
        this.deleteElement = function(id){
        //implementing code to delete this component
        //You can call this API function to remove it
    }
    if (!scope.config.visible){
        //element configuration object
        this.visible(false)}
    }
} })

Then in the main HTML file, include the directive like this:

<div myComm="first" config="eleConfig"></myComp>
<div myComm="second" config="newEleConfig"></myComp>

A separate controller is used for handling the main HTML:

angular.module("baseApp",['componentModule'])
 .controller('baseCtrl',function(){
    $scope.eleConfig = {
      visible:true,
      delete:function(e){
        //This function will run when the delete method is called 
        } 
     }
    //Call the delete method like this:
    $scope.first.deleteElement();
  })

Inquiry How can we trigger the deleteElement() method in the baseCtrl similar to how KENDO UI operates?

Answer №1

Angular follows a pattern of exposing the directive API to the scope in order for directives like ng-model and ng-form to make use of ngModelController and ngFormController APIs.

This is how I would approach it:

angular.module("componentModule",[])
 .directive("myComp",function($parse){
    return{
        replace:true,
        scope: {
            config: '&'
        },
        template:'<h2>This is my component</h2>',
        controller: function($scope) {
            // Add Directive API functions to the directive controller here or in the link function if needed for DOM manipulation
        },
        link:function(scope,element, attr, ctrl){
            // Add to directive controller

            if(scope.config().visible) {
                // Element should be visible, etc.
            }

            ctrl.deleteElement = function(){
                // Call the config.delete method when this function is invoked:

                if(scope.config && scope.config.delete) {
                    // Invoke the config.delete method by calling scope.config()
                    scope.config().delete(element);
                }
            }

            if(attr.myComp) {
                // Assign controller to $parent scope
                scope.$parent[attr.myComp] = ctrl;
            }
        }
      }
   })

If used with markup like:

<div my-comp="first" config="configObject"></div>
<div my-comp="second" config="configObject"></div>

In your base controller:

$scope.first.deleteElement();

or

$scope.second.deleteElement();

will delete the corresponding element.

UPDATE:

The directive has been updated based on your revised question. You can now pass a config object into the directive using an & binding. Since the directive creates a new scope, remember to attach the controller to $scope.$parent.

Answer №2

When it comes to your initial requirement, you mentioned the desire to write the delete function within the directive. However, with KendoUI, the actual implementation of the delete (change) function takes place in the base controller. The delete (change) event is triggered when the component value changes, leading to the execution of the delete function defined in the base controller by the directive. If you aim to emulate the behavior seen in KendoUI, then consider this:

Check out this plunker example

By turning on the browser console, you can view the log. In KendoUI components, the change event occurs automatically when the input element is altered. Nonetheless, in this scenario, I manually initiated the delete event after a 3-second delay.

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

What is the best way to verify and handle an undefined array in order to display an error message?

Currently working on a ternary statement to display the certification of a movie (e.g. PG, R...). If the array length is zero or undefined, I'm aiming to output an error message stating "No Certification Available For This Movie". While I have succes ...

Is there a way to update the parent value when the child is activated?

I need to create a dropdown menu for users to select their email provider - either gmail, hotmail, or outlook. Once they make a selection, I want the button text to update accordingly. The catch is that I can only use bootstrap for this project and cannot ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

Having trouble with the rendering of the Stripe Element Quickstart example

Currently, I am diving into the world of Stripe's Element Quickstart. Take a look at this fiddle that I have been working on. It seems to be quite different from the example provided. Although I have included the file, I can't seem to figure out ...

Implement jQuery to close multiple div elements

My dilemma involves a series of divs with different manufacturer IDs listed as follows: manufacturer[1], manufacturer[2], manufacturer[3], ... etc ... In attempting to create a JavaScript for loop to hide each div, I discovered that it was not achievab ...

Conceal/Inactivate element when scrolling, and once scrolling comes to a halt, reveal it once more

I have been working on creating a div tag to overlay an embed tag and added some javascript to prevent users from right-clicking to download the pdf inside the embed tag (even though it may seem unnecessary, it was requested by my customer). Here is the ma ...

Dealing with alternating rows in a dynamic manner: tips and tricks

Exploring an example scenario: (view live demonstration) Sample HTML structure: <div class="wrapper"> <div city_id="1" class="odd">Street Name #1 in city 1</div> <div city_id="3" class="even">Street Name #2 in city 3</d ...

(node:45207) UnhandledPromiseRejectionWarning: The server has already sent headers, which caused an error

Currently, I am expanding my knowledge of Node.js through the development of a straightforward code snippet application. The application is designed to include two essential fields, namely title and snippet. However, I am encountering a persistent error me ...

VueJS: Preloading data prior to and following component initialization

VueJS is a new technology for me, and I'm currently working on a component that needs to retrieve data from an API before loading the corresponding route. The component should only load once the data is fetched. Additionally, after the component is cr ...

Challenges with dynamically adding rows using jQuery

I am trying to create a dynamic form that allows users to select a project and then populates tasks based on the selected project from a database query. The user can then enter hours for each task, which are updated based on the project id and task id comb ...

Having issues with the right margin in HTML5 canvas and struggling to remove the scroll bar

I am struggling with adjusting the margins of my canvas to ensure equal spacing on both sides without any horizontal scroll bars. Desired Outcome: Equal margin on both sides of canvas without any horizontal scroll bars. Issue: The margin-right property i ...

Error encountered: Invalid symbol detected ('<') while attempting to parse JSON in an Angular application

I am experiencing an issue with my Angular code when trying to submit a form. Upon clicking the submit button, an error saying JSON Parse error: Unrecognized token '<' appears, and empty records are being saved in the database. I have included ...

The ng-repeat track by function is not functioning as expected, displaying slow performance and continuing to create $$hashKey

In my code, I have an ng-repeat setup like this: ng-repeat="article in main[main.mode].primary | orderBy: main[main.mode].primary.filter.order track by article.url" The main[main.mode].primary array contains the data and the .filter.order string is used ...

Issue with AngularJS: Not able to get second app in template to function properly

I have encountered a puzzling issue with my two nearly identical apps. The first one seems to be running smoothly as expected, while the second one doesn't appear to be executing at all. Here is my code (jsfiddle): <div ng-app="passwdtool" ng-con ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

Guide on adding up the value of a property within an array of objects using AngularJS

I am receiving an array of results from a Node.js API in my Angular app, and here is how it looks: <div *ngFor="let result of results"> <div *ngIf="result.harmattan.length > 0"> ... </div> <br> .. ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

Altering content using jQuery

Trying to create a dynamic quiz using HTML, CSS, and jQuery. I am having trouble changing the <p id=question></P> element with jQuery code as nothing happens. Below is my HTML and jQuery code: <!DOCTYPE html> <html lang='es' ...