Send the function to the directive

Below is the code for a directive:

module app.directives {

    interface IDmDeleteIconController {
        doAction(): void;
    }

    class DmDeleteIconController implements IDmDeleteIconController {

        static $inject = ['$scope'];
        constructor(public $scope:any) {
        }

        doAction() {
            console.log('1');
            this.$scope.dmAction();
        }
    }

    export class DmDeleteIcon implements ng.IDirective {

        templateUrl = './app/common/directives/deleteIcon/deleteIcon.html';
        controller = DmDeleteIconController;
        controllerAs = 'dmDeleteIconVm';

        scope = {
            dmAction: '&'
        };

        link = (scope: any, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any) => {
            console.log('2');
            scope.dmAction();
        }

        static factory(): ng.IDirectiveFactory {
            const directive = () => new DmDeleteIcon();
            directive.$inject = [];
            return directive;
        }
    }

    angular.module('myApp').directive('dmDeleteIcon', DmDeleteIcon.factory());
}

This is how I am trying to implement it:

dm-delete-icon(dm-action="console.log('hello');")

Upon opening the page, I see 2 in the console (from the link function), but the hello message from the passed function is not displayed.

Any insights on why this is happening and how it can be resolved?

Update:

Here's the template for the directive:

a.item-detail-delete-icon(class="form-image-link" href="" ng-click="dmDeleteIconVm.doAction()")

The HTML generated by my Jade compiler looks like this:

<dm-delete-icon dm-action="console.log('hello');"></dm-delete-icon>

Update 2:

I attempted to use the directive as follows:

<dm-delete-icon dm-action="vm.foo()"></dm-delete-icon>

where:

    foo(): void {
        console.log("hello");       
    }

is the function defined in the controller.

Update 3:

During debugging of this code, the following output was observed:

https://i.sstatic.net/2eOgk.png

https://i.sstatic.net/kKERj.png

Answer №1

The issue at hand is the directive being given an expression alert('hi'); that will run within the parent controller's scope.

In simpler terms, this implies that the alert function needs to be connected to the scope with a method named alert. Angular expressions do not automatically interact with global objects (alert in this scenario).

To resolve this, make sure the expression passed to the directive is a legitimate angular expression. For instance, create a new method on the app scope labeled myAlert that displays a message and modify the attribute value for the directive to dm-action="myAlert();"

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

Filtering in AngularJs with multiple select options

I am curious about how to create a filter with multiple options. I have a grid with specific settings and column definitions as shown below: $scope.gridOptions = { enableHorizontalScrollbar: 1, enableFiltering: true, p ...

Connecting AngularJS with select options

I am currently developing a checkout feature that calculates shipping prices based on the selected country. If the user picks United States, it should display US. For any other country selection, it should show Not US While the shipping function correctly ...

The field list contains an unidentified column named 'Test.computerIDComputerID'

I am currently navigating through the syntax of typeORM and have been stuck troubleshooting an issue for quite some time. It appears that whenever I utilize the find() function in typeORM, a query is generated with a duplicated column from a relation. Here ...

What is the best way to effectively personalize my Bootstrap variables using SASS?

After creating a web page and adding Bootstrap styling, I attempted to customize the Bootstrap variables, but encountered an issue where it did not seem to work despite no errors being displayed. I followed a tutorial on YouTube meticulously, but to no av ...

Storing user and message data with LocalStorage technology

Seeking advice on a straightforward approach to storing user data and messages. My idea is to use unique key values, such as random tokens (Ynjk_nkjSNKJN) for users, and real ids (1,2,3) for messages. Has anyone encountered this issue before? The goal is ...

AngularJS text markers

In order to streamline the process of managing tags with random content, I have devised a 'tag' manipulation system using the angular-ui alert mechanism. The system includes a factory and a directive as follows: Factory: app.factory( &a ...

Navigating through states in AngularJS

My application has three states: app, app.devices, and app.devices.device. While the first two states are functioning properly, the app.devices.device state is not working as expected. Here is the code for reference: http://pastebin.com/r1kYuExp http://pa ...

What is the best way to assign a value to an option element for ordering purposes?

My select element is being populated with fruits from a database, using the following code: <select name="fruitsOption" id="fruitsOptionId" ngModel #fruitRef="ngModel"> <option *ngFor="let fruit of fruits">{{fruit}}</option> </selec ...

Steps for showing a component (popup modal) just one time with React hooks

Is there a way to implement a popup modal that only appears once using hooks and localStorage? The modal should already appear upon page load. const [showModal, setShowModal] = useState<boolean>(true) return( <ModalIsContractor ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

A step-by-step guide on dynamically binding an array to a column in an ag

I am currently working with the ag-grid component and I need to bind a single column in a vertical format. Let's say I have an array ["0.1", "0.4", "cn", "abc"] that I want to display in the ag-grid component as shown below, without using any rowData. ...

Angular JS unit test for if else statements

I am looking to enhance the code coverage of the branch section by conducting unit tests on the if else statement. However, I am unsure about what exactly needs to be tested in the following code snippet. Controller.js (function () { "use strict"; ...

Utilize associative arrays to efficiently filter ng-repeat

Having an associative array (or object to be more precise) $scope.items = { 'x': {...}, 'y': {...} }; Wanting to use ng-repeat which is functioning properly <div ng-repeat="(id, data) in items | filter: customFunction" > But t ...

What is the solution for getting rid of the "clear sort" state in an angular-ui-grid column header?

I am looking for information on how to remove the default behavior where the 3rd click disables sort and stays "neutral" on sortable headers. Having a disable sort state seems flawed as it does not change the sort order. How can I eliminate the 3rd state ...

Unable to establish a connection between the HTML element and the TypeScript variable

I'm facing an issue with my code where the function that worked perfectly for register and login is not functioning properly on the index page. Even though there seems to be no errors in the login and register functions, I have a form with an input s ...

Troubleshooting tsconfig configuration issue in Visual Studio Code for ExpressJS with TypeScript and Vitest integration testing

Let's dive right in with an illustration: Here is a simplified version of my project structure: src/ app.ts test/ integration/ example.spec.ts tsconfig.json tsconfig.json The main tsconfig.json file includes these settings: { & ...

Using AngularJS to establish a connection with a remote server

I am working with a secure Restful API (localhost:8180) that requires authentication. I am using Angular JS HTTP services to log in to the server and retrieve data from localhost:8180/api/version/?1 (just an example). Below is the code snippet: //Config ...

What is the best way to implement multiple ternary operators within HTML code?

Consider the following code snippet: It currently applies CSS classes up to red4, but I want to apply CSS classes up to red11. Additionally, the variable "size" in myData should be dynamic. For example, size could range from 0-20 // 0-100 // 0-10000, etc., ...

Understanding the npm install command

I'm trying to understand how npm install actually functions. Shouldn't it have automatically installed all the dependencies listed in package.json? I visited the documentation npm install npm install (in package directory, no arguments): ...

Can FLASK be integrated within the AngularJS ng-app <html ng-app> framework?

I have been working on a project that was built using FLASK and Jinja2 templates. This web application allows users to log in and view their profiles online. Currently, I am looking to enhance the project by integrating AngularJS ...