What are the best ways to prioritize custom events over ng-click events?

Recently, I developed a web application using AngularJS. One of the features I included was an input text box with a custom ng-on-blur event handler.

Due to some issues with ng-blur, I decided to create my own custom directive called ngOnBlur. Here's how it appears in my code:

app.directive('ngOnBlur', function($parse){
    return function(scope, elm, attrs){
            var onBlurFunction = $parse(attrs['ngOnBlur']);
            elm.bind("blur", function(event) {
                scope.$apply(function() {
                    onBlurFunction(scope, { $event: event });
                })});
    };
});

The problem arises when I enter text into the textbox and then quickly click on another button in my app (which triggers a ng-click event). Unfortunately, the ng-on-blur event does not get triggered at all and the click event takes precedence.

I'm looking for suggestions on how to adjust the priority of my custom event. Here is what the html currently looks like:

<input type="text"  ng-model="x.y" ng-on-blur="doSomething()" />

I have even tried setting the priority to 100 but it doesn't seem to solve the issue. Any advice or solutions would be greatly appreciated.

Answer №1

Is there a way to adjust the priority of a custom event?

If you want to change the priority of a custom directive you created, you can specify the priority attribute. By default, it is set to 0.

Here's an example:

HTML

<input type="text"  ng-model="x.y" on-blur="doSomething()" />

     <button ng-click="init();">press  me</button>

JS

app.controller('fessCntrl', function ($scope) {
    $scope.doSomething = function(){
       console.log('doSomething');
    };

     $scope.init = function(){
       console.log('init');
    };
});

app.$inject = ['$scope']; 

app.directive('onBlur', function() {
    return {
            restrict: 'A',           
            link: function(scope, elm, attrs) {
                    elm.bind('blur', function() {
                            scope.$apply(attrs.onBlur);
                    });
            }
    };
});

Check out the demo on Fiddle

Answer №2

It has become clear to me why it isn't working now.

Upon clicking the event, I realized it was on a sortable element from jQuery UI. Could this be affecting the priority?

I am clicking on a draggable element that follows this structure:

<ul my-sortable id="sortable">
    <li ng-repeat="item in items">
        <div ng-switch on="item.type">
             <div ng-switch-when ="x" ng-click="doSomething"></div>
        </div>
    </li>
 </ul>

Here is the code for my sortable feature:

app.directive('mySortable',function(){
return {
link:function(scope,el,attrs){
  el.sortable({
    revert: true,
    stop: function(event,ui){
        ui.item.height("auto");
    }
  });
  el.disableSelection();

  el.on( "sortdeactivate", function( event, ui ) {
    var from = angular.element(ui.item).scope().$index;
    var to = el.children().index(ui.item);
    console.log(from);
    console.log(to);
    if (to >= 0) {
      scope.$apply(function(){
        if (from >= 0) {
          scope.$emit('my-sorted', {from:from,to:to});
        } else {
          scope.$emit('my-created', {to:to, index:angular.element(ui.item).attr("data-index")});
          ui.item.remove();
        }
      })
    }
  } );
}

} });

If anyone knows what I should do next, please advise. Thank you!

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

unable to auto-populate drop-down selection based on selected value in AngularJS

Currently, I am implementing a drop-down within an ng-repeat loop in AngularJS. Here is the HTML code snippet: <select class="form-control" ng-model="l.Language" ng-change="languageChange($index, l.Language)" ng-options="L.ID as L.LanguageDDL for L i ...

"Enhance your React application with react-router-dom by including parameters in the index URL while also

Here is the code I am currently using: <Router history={history}> <div> <Route exact path="/:id?" component={Container1} /> <Route path="/component2/ component={Container2} /> </div> </Router> When accessin ...

Passport Local Strategy Custom Callback in Node.js Fails to Execute Serialize and Deserialize Functions

I am currently working on integrating Passport with a custom callback on a local strategy. Using AngularJS in the frontend and nodejs along with express on the backend. So far, I have managed to complete the entire workflow. However, I am facing an issu ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

Encountered an issue while integrating CKEditor 5 into a standalone Angular 17 application: "Error: window is

Having trouble integrating CKEditor with my Angular app (version 17.1.2 and standalone). I followed the guide step by step here. Error: [vite] Internal server error: window is not defined at r (d:/Study/Nam3_HK3/DoAn/bookmanagement/fiction-managemen ...

Imitate the act of pasting content into a Textarea using JavaScript

When data is copied from the clipboard and pasted into an html textarea, there is some interesting parsing that occurs to maintain the formatting, especially with newlines. For instance, suppose I have the following code on a page that I copy (highlightin ...

Strategies for efficiently retrieving delayed ajax data to display in a Rails view

When working with an API action that takes around 10 seconds to retrieve data, I typically use an alert to ensure the data is successfully fetched. However, my main concern is how to effectively transmit this data to a Rails view for displaying purposes. B ...

In React Native, you can pass native component properties as props, while also defining custom ones using a TypeScript interface

I am working on a component called AppText where I need to utilize a Props interface and also be able to accept additional props that can be spread using the spread operator. However, I encountered this error: Type '{ children: string; accessible: tru ...

Master the art of crafting precise searches with Js and Jquery

In my quest to create an expanded search function that allows users to find people not only by their names but also using various combinations, I encountered a challenge. For example, I have a list of players and the following code snippet works fine: ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

Tips for populating several input fields using an ajax callback

I have a functioning code below that needs to update input fields with values retrieved from an ajax call. I am unsure about the ajax success function that would allow me to callback php variables ($first, $last, etc.) to populate those input fields. Your ...

The mobile navigation in HTML has a slight issue with the ::after pseudo-element, specifically within the

As I prepare to launch my website, I have made adjustments to the mobile layout by moving the navigation links to a navigation drawer. The template I am using included JavaScript scripts to handle this navigation change. However, I encountered an issue whe ...

Web performance issues noticed with Angular 8 and Webpack 3.7 rendering speed

My web application is currently taking 35 seconds to render or at least 1.15 seconds from the initial Webpack start. I've made efforts to optimize Webpack, which has improved the launch speed, but the majority of time is consumed after loading main.j ...

Limit express to only allow AJAX requests

Currently working on an Express app where I aim to restrict access to the routes exclusively through AJAX requests. Aware that this involves using the X-Requested-With header, but uncertain of how to globally block other request types. Any suggestions or ...

How to properly display date format in Node.js when using EJS templates with MySQL

When retrieving dates from the database, I am looking to break them down into two separate numbers. 7:00-8:00 //array[0]=7:00 and array[1]=8:00 9:00-9:30 14:30-15:00 Below is my code, but it is returning NaN NaN: <% time_slots.forEach((timeslot ...

Fetching SFTP directory listings asynchronously using Node.js

I'm currently working on fetching SFTP listings using Node.js from multiple servers. To achieve this, I am utilizing the ssh2-sftp-client library and trying to manage the asynchronous connections by implementing a customized Promise.all() approach. T ...

Unexpected Timed Out error from Socket.IO adapter when MongoDB connection is lost

I have been experimenting with capturing the disconnection event in mongodb. Everything is working smoothly with this setup: simple.js 'use strict'; var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:2701 ...

Error message received while converting webm video to images using Kagami/ffmpeg.js: Unable to locate an appropriate output format for '%04d.jpg'

These are the current versions: node v12.9.1, npm 6.10.2, [email protected] Repository: https://github.com/Kagami/ffmpeg.js The code in decode.js looks like this: const fs = require('fs'); const ffmpeg = require('ffmpeg.js'); c ...

Warning: Nodemailer has issued a deprecation warning regarding the outdated `punycode` module

Looking to automate daily email sending through a Gmail account, I have been experimenting with nodemailer and crafted this simple test code: const fs = require('fs'); const path = require('path'); const nodemailer = require('nodem ...

I am interested in learning how to utilize jQuery to decode JSON Unicode within a Select2 dropdown filtering system

I am currently utilizing Select2 JS and Datatables JS to handle data in JSON format. However, I encountered an issue where the value Animal & Veterinary is displayed differently in JSON as Animal \u0026amp; Veterinary, and on the Select2 filter as ...