Attach a click event to a dynamically generated element inside a directive

After thinking I had successfully solved this issue, it turns out I was mistaken. I developed a directive to enable me to clear a text input field. Essentially, when you begin typing into the input box, an "X" icon appears on the right side of the textbox. Clicking on this icon erases the model. Below is the code for my directive.

(function() {
    "use strict";
    var app = angular.module("myApp");

    app.directive("clearInput", ['$compile', function ($compile) {
        return {
            require: 'ngModel',
            scope: {},
            link: function (scope, element, attrs, ngModel) {

                if (element.next().length) {
                    element.next().insertBefore(element);
                }

                var tpl = '<span> <i class="icon ion-close-circled placeholder-icon clear-element"  ng-show="show" ></i></span>';
                var clear = angular.element(tpl);

                scope.setValue = function (val) {
                    ngModel.$setViewValue(val);
                    ngModel.$render();
                    scope.$apply();
                };

                clear.on('click',
                function () {
                    scope.setValue(null);
                });

                element.bind('blur', function () { scope.setValue(ngModel.$modelValue); });

                scope.$watch(function () {
                    return ngModel.$modelValue;
                }, function (val) {
                    scope.show = val === null ? null : val.length > 0;
                });

                $compile(clear)(scope);

                element.after(clear);
            }
        }
    }]);
})(); 

When I initially created and tested the directive using Plunker, I unknowingly included a very old version of Ionic (1.0.0-beta.5). Surprisingly, the directive worked perfectly under this circumstance.

http://plnkr.co/edit/5rGzl1?p=info

Upon transferring the directive to my application environment, I encountered an issue where the click event I bind doesn't trigger. To troubleshoot, I forked the Plunker and utilized an updated version of Ionic (1.0.1). In this case, the click event did not work (though interestingly enough, the double-click did).

http://plnkr.co/edit/DH6jjG?p=info

If anyone has insights on how to resolve this matter, your assistance would be greatly appreciated! Thank you!

Answer №1

I checked out the second link you provided and made a slight adjustment:

clear.on('click',
                function () {
                    scope.setValue(null);
                });

I changed it to:

element.on('click',
                function () {
                    scope.setValue(null);
                });

It appears to be functioning correctly now. Please confirm if this aligns with your intended outcome :)

Answer №2

By switching out the label tag with a different one, such as a div tag, in the home.html file, you can make it work in some way. However, this method may cause you to lose the label's original features (like focusing on the input when clicking on the label text).

I attempted to search for an explanation in the ionic changelogs but found nothing relevant (Ionic changelog). Perhaps it would be beneficial to create a new issue on their Github project: Ionic issues.

Answer №3

After reaching out to the Ionic GitHub support team, I received this helpful response:

The reason for this behavior is due to our use of labels to focus on input fields. When a label element is clicked, tapped, or touched, it will try to set focus on an associated input.

To achieve your desired outcome, substituting a div for a label should suffice.

Therefore, simply wrapping my element in a DIV (as I have already done as a temporary solution) seems to be the only necessary action.

You can find more information about this issue in the following ticket:

https://github.com/driftyco/ionic/issues/4205

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

Navigate to the chosen item in material-ui scroll bar

Currently, I have a list created using material-ui which contains numerous items and displays a scrollbar due to its size. I am looking for a way to automatically scroll to the selected item within the list. Does anyone have any suggestions on how I can a ...

The Vue component with the export default directive could not be located

Whenever I try to create a dashboard component, I keep encountering the same error in my command prompt. "export 'default' (imported as 'DashboardLayoutComponent') was not found in '@syncfusion/ej2-vue-layouts' Has anyo ...

changing the core JavaScript of a keyboard plugin

To access the demo, click on this link: . You can find the main javascript file at https://raw.githubusercontent.com/Mottie/Keyboard/master/js/jquery.keyboard.js. Is there a way to switch the positions of the accept and cancel buttons? ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

What is the best way to loop through values in a complex JSON structure?

After retrieving data from the "Orders" collection in Firebase Firestore, I am facing an issue with fetching a specific value from the object. The code for fetching data from Firebase is as follows: app.get('/trial',(req,res)=>{ const orders ...

Discovering the method for keeping track of file changes and executing find-replace operations without registering it as an event within the monitored file

I am confused about why the output displays two lines when typing 'fizbuzz' into the test.txt file. I understand that it is performing a find and replace operation, but how can I avoid it being triggered by the watch function? const watch = requ ...

What are some tips for integrating Bluebird into Angular frameworks?

I attempted to integrate Angular with Bluebird promises: Here is the HTML code snippet: <body ng-app="HelloApp"> <div ng-controller="HomeController">{{name}} {{also}}</div> </body> The corresponding JavaScr ...

Error 401 encountered while accessing the Binance API using Ionic and Angular

function makePrivateCall(apiSecret, apiKey, endpoint, data = null, isGetRequest = true) { const timestamp = Date.now(); const recvWindow = 60000; //maximum allowed, default 5000 var obj = { apiSecret, ...data, timestamp, ...

get a duplicate of an object

Is this the proper method for creating a duplicate of an object? class ObjectWrapper { private _obj; /*** * Copy object passed as argument to this._obj */ constructor (_obj: Object) { this._obj = _obj; } /** Return copy of this._ ...

Obtain an Element Using Puppeteer

Currently grappling with a sensitive issue concerning puppeteer. The HTML structure in question is as follows: <tbody> <tr rel="0" class="disabled" id="user6335934" class="odd"> ...

An overabundance of parallax visuals

I'm currently working on a static website that features several parallax images dividing each section. However, I've run into an issue as I continue to add more sections and parallax images. Some of the images at the bottom of the website are shi ...

Bandcamp API sales data retrieval feature

Looking for assistance with a call to the Bandcamp API. Every time I request /http://bandcamp.com/api/sales/1/sales_report/, I receive this message in the response: /"error_message":"JSON parse error: 757: unexpected token at ''/ ...

Search within the XML document for each JavaScript request, and then iterate through another set within the main

I have been developing an Android application using the PhoneGap framework. I created a PHP-XML file to extract data from my website to the application. However, I am facing an issue where I want to display all the <vic></vic> content associate ...

When using Angular 2 Forms, the formControl.touched property will only be set to true when the text area is clicked, rather

Below is a form I am working with: <form *ngIf="showForm" [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)"> <textarea type="text" placeholder="Description" [formContro ...

Activate the Select List to Appear Only When a Search is Conducted

Currently, I have implemented the react-select API in order to provide language options for selection. <Select isMulti name="langs" options={langOptions} defaultValue={{ value: "English", label: "English", nativeNam ...

Updating a specific row in a multiple row form can be achieved when the input field names match in a column

My task involves working with a report that generates a form in input mode. This form contains multiple rows of data, each row consisting of a button and an input field. The input field name remains consistent across all rows for easier processing by the C ...

Creating an engaging user experience with a Django form

Creating a dynamic calculator <div id="calculator"> <h2>Calculate the price of sawing materials</h2> <form method="post" action="{% url 'products' %}"> {% csrf_token %} & ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

I am experiencing an issue where the Ajax/Javascript functionality is unresponsive on my homepage

I have been attempting to design a button using a simple Ajax / Javascript command. It seems to be functioning properly, but I am encountering an issue where it does not appear on the main page when inspecting with F12, causing some complications. Below i ...

Searching through an array based on a specific string

Could someone lend a hand in getting this to function... The code snippet below is functioning const acco = [{FullyQualifiedName=(-) Imposto Unico, Id=109, sparse=true, AcctNum=3.1.2.01.03027}, {FullyQualifiedName=13º Salário, Id=114, sparse=true, AcctN ...