Discovering a div within an element using an Angular TypeScript directive

I've been working with TypeScript in an Angular project.

Recently, I created a directive that consists of a div containing text and a close button with the class name 'block-close'.

Now, my challenge is to implement a click function for the close button within the directive.

How can I add a click event to a button that is nested inside the directive?

I've attempted various approaches like:


angular.element('.block-close').on('click', function(){
    alert('Clicked!');
});

angular.element(document).find('.block-close').on('click', function(){
    alert('Clicked!');
});

(() => {

    class MyDirective implements ng.IDirective{

        public restrict = 'E';
        public scope = {};
        public controller = 'MyController';
        public controllerAs = 'myCtrl';
        public bindToController = true;
        public templateUrl = "mysite.html";

        constructor(){

        }

        link = (scope, element, attrs) => {
            angular.element('.block-close').on('click', function(){
                alert('Clicked!');
            });
        };

    }

    angular.module('myMod').directive('myDirective', () => new MyDirective());

})();

Answer №1

If you have a file called "mysite.html" with code similar to this:

<div>
<input type="button" value="close" class="block-close"/>
</div>

And you need to manage the click event for the button with the class "block-close".

You can simply add a function within the link function like so:

link = (scope, element, attrs) => {
                scope.closeClicked = () =>{
                           alert("clicked..");
                     }
            };

Then, update your "mysite.html" as follows:

<div>
    <input type="button" value="close" ng-click="closeClicked()" class="block-close"/>
</div>

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 uploading a file to an Angular component and transmitting it through HTTP

Currently working on a project that involves the following files: app.component.html <div> <input type="file" ([ngModel])="file" accept="application/pdf" onChange="change()"> </div> app.module.ts: file: File = null; change(){ ...

The Sanity npm package encounters a type error during the build process

Recently, I encountered an issue with my Next.js blog using next-sanity. After updating all npm packages, I found that running npm run build resulted in a type error within one of the dependencies: ./node_modules/@sanity/types/lib/dts/src/index.d.ts:756:3 ...

When initialized within an object, Angular may identify a field as undefined

Whenever I attempt to access a property of the object named "User," it shows up as undefined. However, upon logging the complete object to the console, the field appears with the necessary data. Here is the console log output: perfil.component.ts:42 unde ...

Definition of the default export function type

Trying to create a typings definition for the pouch-redux-middleware library, which consists of a single function: import PouchMiddleware from 'pouch-redux-middleware' PouchMiddleware({...}) This is the typings definition that has been attempt ...

In TypeScript, what do we call a property that is accessed dynamically?

I have a reusable function that can be used on various properties of a custom type. Here's an example: interface MyType { prop1: string; prop2: number; } type MyTypeKey = keyof MyType; const testValue = ( obj: MyType, property: MyTypeKey, v ...

Angularfire allows for easy and efficient updating of fields

Currently, I am working on creating a basic lateness tracker using AngularFire. So far, I have successfully added staff members to the miniApp and set the initial late minutes to a value of 0. My challenge lies in updating these values. Ideally, when a us ...

Data cannot be displayed in a grid using Kendo UI and AngularJS within an ASP.NET MVC framework

Currently utilizing KendoUI and AngularJS in my ASP.NET MVC 4 project. I am attempting to retrieve data from the database and display it in a grid, but unfortunately, the grid is not showing any data. The data has been successfully downloaded from the db a ...

Issue: Unable to locate 'storysolo' from state 'index'

On my index.php page, I have a ui-sref link set up like this <a ui-sref="storysolo({ storyId: headline.nid })"> Additionally, my main js file is loading the angular code in the following manner var rebelFleet = angular.module("CougsApp", ["ui.ro ...

Associate the generic operator <T> with a FunctionConstructor

In my TS function, I deserialize JSON into a specific type/object by providing it with a constructor function of that type which reconstructs the object from JSON. Here is how it looks like: export function deserializeJSON<T>(JSONString: string, ty ...

Protractor experiencing sluggish performance on Internet Explorer11

When using Protractor to run my test cases in Internet Explorer 11, I noticed that it takes significantly longer compared to Firefox and Chrome. It even takes around 20 seconds just to enter the text "Hello" into a text box. Is there a way to improve the ...

Utilizing Angular for making API requests using double quotes

I am experiencing an issue with my service where the double quotation marks in my API URL are not displayed as they should be. Instead of displaying ".." around my values, it prints out like %22%27 when the API is called. How can I ensure that my ...

Troubleshooting Problem in Coursera's AngularJS Week 3 Exercise 4

Here's the issue I'm facing: After launching the index page with 'gulp watch', there's nothing visible on the screen. An error appears: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.12/$injector/modulerr?p ...

Trouble with $scope.currentPage not updating correctly in Angular UI Pagination

Recently, I've been working on this codepen project. In it, I'm utilizing the function '$scope.pageChanged' to monitor page changes. $scope.pageChanged = function() { $log.log('Page changed to: ' + $scope.currentPage); }; H ...

Leveraging an array of Elasticsearch documents using AngularJS

The query results are given below... { "took": 6, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 45, "max_score": 0, "hits": [] }, "aggregations": { ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

Perform an individual HTTP request one time only

I am developing an AngularJS application and I have a scenario where I need to make an HTTP post request within the controllers of certain views, but I only want this request to run once. I attempted to accomplish this by using the following code: aldro_a ...

AngularJS fails to trigger window scroll event

Although I have come across similar inquiries regarding this issue, none of the solutions have proven to be effective for me. Currently, I am working with AngularJS and I am attempting to detect the scroll event. Despite trying numerous variations to capt ...

Create a separate folder for templates within Angular to serve as the functional equivalent of a views folder

When attempting to use the ERB template in my Angular templates folder, I am encountering some limitations. For example, using <% link_to %> works fine, but when trying to utilize devise methods or even raw('sdmdslkc'), an error is triggere ...

What is the best way to display ng-repeat elements in a horizontal layout

Looking for a way to display thumbnails horizontally using ng-repeat in AngularJS and Bootstrap. Any ideas on how to achieve this with CSS or Bootstrap? <div class="row"> <ul class="col-md-4" id="phones"> <li class="thumbnail" ...

Password validations are a key feature of reactive forms

Currently, the sign-up button only becomes enabled if the signup form is valid. However, I am facing an issue where the button is getting enabled even when the password and confirm password fields do not match. I suspect there might be a problem with my i ...