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

Guide to implementing if else statements with Protractor

I am facing some unusual situations and I'm not quite sure how to address them. As a newcomer to testing, I've been tasked with testing a website's cart function for proper functionality. The challenge arises when we add a certain number o ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Show a directional indicator on hover in the date selection tool

I am currently using a datepicker that looks like this: When I hover over it, three arrows appear to change days or show the calendar. However, I would like to remove these arrows. Here is the code snippet: link: function (scope, element, attr, ngModel ...

Tips for arranging a group of objects based on a nested key within each object

i have a collection of objects that I need to sort based on their id. here is the information: { 1918: { id: "1544596802835", item_id: "1918", label: "Soft Touch Salt Free Mint 500 ml (000001400045)", combo_items: false } 6325: { ...

Adding an image to a Select Option label in React: A simple guide

As a newcomer to React, I am experimenting with creating a drop-down menu that includes images in the labels. My approach involves using a function to gather values from a map and construct an id: label pair to display as options in the drop-down. Both the ...

What is the best way to show an on/off button in an HTML page when it loads, based on a value stored in a MySQL database?

Is there a way to display a toggle button onload based on a value from a MySQL database table? I need the button to switch between 0 and 1 when clicked. I've looked at several solutions but none of them seem to work for me. Any help would be greatly a ...

The scrollbar will be visible only when the mouse hovers over the table

I have been experimenting with customizing the scrollbar appearance of an ant design table. Currently, the scrollbar always displays as shown in this demo: https://i.stack.imgur.com/vlEPB.png However, I am trying to achieve a scroll behavior where the sc ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

Sliding divider across two div containers with full width

Seeking a JavaScript/jQuery function for a full page slider functionality. The HTML structure I'm working with is as follows: My objectives are twofold: Both slide1 and slide2 should occupy the full width of the page. Additionally, I am looking for ...

Optimal method for conducting Jasmine tests on JavaScript user interfaces

After exploring the jasmine framework for the first time, I found it to be quite promising. However, I struggled to find a simple way to interact with the DOM. I wanted to be able to simulate user interactions such as filling out an input field, clicking ...

What could be causing the 404 error I'm receiving for this specific URL?

Can someone explain why I keep encountering a 404 error when I type \book into the URL bar? Below is the code I am currently using: var express = require('express'), app = express(), chalk = require('chalk'), debug = ...

Tips for isolating data on the current page:

Currently, I am using the igx-grid component. When retrieving all data in one call and filtering while on the 3rd page, it seems to search through the entire dataset and then automatically goes back to "Page 1". Is there a way to filter data only within th ...

Guide on sending two values from a form using Ajax and the POST method

How can I send two values, A and B, from a form to check.php using Ajax with the POST method? In the code snippet below, I managed to send two input values to check.php and assign them to variables $A and $B. However, I want to accomplish this without ref ...

I'm encountering an issue where I receive the error `Cannot read property 'map' of undefined` while attempting to integrate the backend with React. What could be causing this error and how

I'm currently learning React and I've been using a tutorial here to connect my database to the front end of my React application. Unfortunately, every time I try running 'npm start' at 'localhost:3000' in express-react/backend ...

I am having issues with Hot Reload in my React application

My app was initially created using npx create-react-app. I then decided to clean up the project by deleting all files except for index.js in the src folder. However, after doing this, the hot reload feature stopped working and I had to manually refresh the ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

Is there a way to retrieve the properties of another function within the same component?

I am trying to place NumberFormat inside OutlinedInput and I also need different properties for the format of NumberFormat. (There will be a select window that defines which format property to use). This is what I have: import OutlinedInput from "@ma ...

`The challenge of a single web page not displaying correctly`

I was working on a website for a local computer building company, and I decided to make it a single-page applet. The HTML is mostly done, and I don't have much trouble with CSS. However, I encountered an issue with hiding and displaying different sect ...