Executing a function after an AngularJS directive's reference function has been called

<CustomDirective customValue="someValue"  anotherFunctionRef="anotherFunction()"></CustomDirective>
angular.module('AppName', ['OtherDependencies']).
        directive('CustomDirective',
                function($timeout) {
                    return {
                        restrict: 'AE',
                        replace: 'true',
                        template : 'Some HTML Content',
                        scope: {
                            value1: '=customValue',
                            value2: '&anotherFunctionRef',
                        },
                        link: function(scope, watch){
                            
                        }
                    };
                });
  1. This is an angular JS custom directive that passes a reference of a method from the HTML to be called.
  2. Our goal is to also execute another function after the referenced function (value2) has finished running.

Since we cannot call a common function directly from the HTML or parent controller, we need to call it from within the angular directive itself after the execution of the referenced function (value2).

Answer №1

It appears that you may still be utilizing Angular 1. If this is the case, please refer to the following link for assistance. Alternatively, if you are using a version of Angular greater than 2, look into the 'output' eventEmitter.

1. http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx
2. https://stackoverflow.com/questions/47639275/using-emit-to-pass-a-function-from-child-to-parent-in-angularjs

Answer №2

angular.module('ProductApp', ['ngRoute']).
        directive('CustomDirective',
                function($timeout) {
                    return {
                        restrict: 'EA',
                        replace: true,
                        template : 'This is a custom HTML template',
                        scope: {
                            data1: '=info1',
                            Data2: '&callbackFunction',
                        },
                        link: function(scope, element, attr){
                            scope.Data2 = function(){
                                
                                scope.$parent.$eval(attr.callbackFunction);
                                
                                /* additional code goes here */ 
                            }
                        }
                    };
                });

Overriding functionality in AngularJS directives using $eval() to call referenced functions

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

Tips for successfully parsing JSON data during an Ajax call

After making an Ajax call, the response.responseText I receive looks like this: . "[ columns :[ { "id":"name", "header":"User name" }, { "id":"birth", "header":"Date of birth" } ], ...

Redux saga will halt all other effects if one fails during execution

Having some trouble with yield all in saga effect, I've included a snippet of my code below function* fetchData(item) { try { const data = yield call(request, url); yield put(fetchDataSuccess(data)); } catch (error) { yield put(fetchDa ...

'this' while being utilized in a nested function

const EventEmitter = require('events').EventEmitter; const Counter = function (init) { this.increment = function () { init++; this.emit('incremented', init); } } ...

Obtaining and Assigning Filter Values in Material Table

Is there a way to programmatically obtain and adjust filter values with material-table? I am looking to enable users to save filter settings as reports and access them whenever necessary. ...

Having trouble notifying a json object following an ajax request

My project involves using a PHP file that contains an array with multiple values. Additionally, I have an HTML page that features a single input field. A listener is set up to detect changes in the input field. Once a change occurs, an AJAX call is trigge ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

What is the best way to selectively adjust object parameters in unit testing?

In my module, I have an object with several parameters. I want to rewire only specific parameters of this object. Here is a snippet from my 'module.js' file: var obj = { param_A: 'valueA', param_B: 'valueB', param_C: &a ...

The useNavigate() function seems to be failing to redirect to the '/protected' route

The issue lies in the redirection process after receiving the token from the API. Although the token is successfully saved in local memory, the redirect to the intended page does not occur as expected. Instead, a manual window refresh is required to naviga ...

Unable to load custom package in Angular 2 testing environment

I've been following the official Angular 2 testing guide on an existing project. Everything runs smoothly when I use my custom library, downloadjs, in the application. However, I encounter an error in the console during test execution: "__zone_symbol ...

Encountered a RunTime Error when attempting to Lazy Load a module

When attempting to lazy-load a component separately, an unexpected run-time error is occurring. This issue is specifically related to writing loadChildren within the routing module of another component in Angular 6. Any assistance with resolving this error ...

Tips for displaying a jQuery error message when a key is pressed

I am working with a textarea that has a word count limit of 500. I need to display an error message below the textarea if the word count exceeds 500. I have successfully calculated the word count, but I am unsure how to display the error message and preve ...

Is there a way to utilize regular expressions in React to dynamically insert onclick events into specific words within a text block?

I've been experimenting with regular expressions in React to implement an onclick event for each word in a text. I've attempted two different strategies, but neither has been successful thus far. Initially, I tried: return( <div> & ...

Switch Between Different Background Colors for Table Rows With Each Click

This script changes colors when a row in a specific column is clicked: $(document).ready(function(){ $("#rowClick").children("tbody").children("tr").children("td").click(function(){ $(this.parentNode).toggleClass("enroute"); }); }); CSS: .placed{ b ...

What is a method for saving a file from Chrome to a network drive using scripting language, even though it's currently functioning in IE?

In a SharePoint 2013 document library, I have implemented a JavaScript function that captures user access to files. The function creates a .txt file containing information about the user ID, username, and file path, which is then saved to a network drive l ...

I can't figure out why this form isn't triggering the JS function. I'm attempting to create an autocomplete form field that connects to a MySQL database using a PHP script and AJAX

I am encountering an issue while trying to implement the .autocomplete() function from jQuery UI with a list of usernames fetched from a MySQL database using a PHP script. Strangely, it is not functioning as expected and no errors are being displayed in th ...

Inability to submit page after clicking on lower half of button while eliminating validations

In my current Struts2 application, I am encountering a issue related to validations on textfields. The validations include checks for missing values and incorrect values. Below these fields, there is a button that should submit the form once all validation ...

JavaScript: A guide to substituting specific characters in a string

I attempted to extract a list of names from a URL as URL parameters. var url_arrays = [],url_param; var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < url.length; i++) ...

Parsing JSON data in JavaScript

I am facing an issue with parsing JSON using JavaScript. After the completion of the loop, my variable 'text' is not getting the expected result. Can someone please explain how I can correctly parse this JSON? var xmlr = null; var text = '& ...

Execute the dynamic key API function

Below is the data object: registration: { step1: { project: '', }, step2: { adres: '', facade: '', floor: '', }, }, An attempt is being ...

Route.get() function is expecting a callback function, but instead received a string object

Having searched through similar posts, I am unsure and lack the experience to apply the suggested resolutions to my project. I recently built a basic app with two main routes as part of a Udemy course, but I am struggling with the following error: "Route.g ...