Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data and store it in the browser's local storage.

<input ng-blur="functionName()" />

The traditional approach works well for single inputs, but what if there are multiple inputs:

<input ng-blur="functionName()" />
<input ng-blur="functionName()" />
<input ng-blur="functionName()" />
<input ng-blur="functionName()" />

Is there a way to apply the ng-blur effect to all inputs on a page without individually adding the ng-blur attribute to each one?

Answer №1

If you want a custom directive that can handle this task, consider the following solution which was inspired by a response to a similar query:

AngularJS 1.3 - Implementing `ng-change`-like feature for the entire form

While this code hasn't been tested yet, it should provide you with a good starting point:

.directive('inputsOnBlur', ['$parse', function($parse){
  return {
    link: function(scope, element, attrs){
       var cb = $parse(attrs.inputsOnBlur);
       element.find('input').on('blur', function(){
          cb(scope);
       });
    }
  }
}]);

To utilize this directive, follow the below example:

<form inputs-on-blur="doSomething()">
   <input />
   <input />
   <input />
</form>

Answer №2

Absolutely, it's totally doable. You just have to dynamically include data-ng-blur in the input tag. Here is an example of the code you can use in your controller:


    var inputs = Array.prototype.slice.call(document.getElementsByTagName('input'));
    inputs.forEach(function (input) {
        input.setAttribute('data-ng-blur', 'functionName()');
        $compile(angular.element(input))($scope);
    });

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

Perform the same actions on every element within the ul li

I'm facing an issue with my unordered list, where each list item contains a span element with an image inside. My goal is to set the background-image of each span to be the same as the image it contains, while also setting the opacity of the image to ...

Discovering and revising an item, delivering the complete object, in a recursive manner

After delving into recursion, I find myself at a crossroads where I struggle to return the entire object after making an update. Imagine you have an object with nested arrays containing keys specifying where you want to perform a value update... const tes ...

Stop any accidental double clicks on the <input type="submit" /> to avoid duplicate entries

Is it possible to prevent a user from clicking twice on an input tag button with type submit? I attempted using ondblclick="javascript:void(0)", but it did not work. My code is within an Html.BeginForm, not a form element tag. Thank you in advance for al ...

Hide the menu when a user taps on an item on mobile or tablet devices

I'm facing a unique challenge and could use some guidance. The issue is with the mobile version of my website, accessible at . On tablets or mobile devices, the menu is condensed into a button. To navigate through the menu, I have to click the button ...

The counterpart of the RxJS setTimeout operator

Looking for a RxJS operator alternative to set/clearTimeout in these circumstances: this.mouseEnterSubscription = this.mouseEnterStream .subscribe(() => { this.timeout = setTimeout(() => { void this.playVideo(); }, 500) }); this.mo ...

What are the best ways to handle processing of incorrect input?

I created a custom validator to prevent the form from being submitted with invalid data, and as an added bonus, I noticed that the input is not processed when it's invalid - for example, ng-change isn't triggered even though the input is changing ...

When running npm install, the dist folder is not automatically generated

I found a helpful tutorial at this link for creating a Grafana plugin. However, when I tried copying the code from this link to my test server (without the dist/ folder) and ran npm install, it did not generate a new dist/ folder but created a node_module ...

utilize dynamic variable within the template's views

Here is a snippet of my HTML code var marker; function initMap() { map = new google.maps.Map(document.getElementById("mymap"), myOptions); getMapMetadata([]); // setInterval(function(){ getMapMetadata([]); }, 3000); } function createMarke ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...

Implementing Material UI datetime-local feature with no minute selection

Is there a way to hide minutes in a TextField with type = datetime-local? <TextField label="From" type="datetime-local" InputLabelProps={{ shrink: true, }} /> This is how it appears on my end: screenshot ...

What is the best way to implement my custom toolbar button to utilize the form's validation function within react-admin?

I have developed a unique Toolbar with a custom button that is supposed to mimic the behavior of the standard SaveButton but also perform additional actions after the form is submitted. The form should only be able to submit if it passes validation, and an ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

Having trouble importing a file in TypeScript?

I needed to utilize a typescript function from another file, but I encountered an issue: I created a file called Module.ts with the following code snippet: export function CustomDirective(): ng.IDirective { var directive: ng.IDirective = <ng.IDire ...

Creating a gradual appearance effect through ng-repeat when adding elements to the beginning of a list

I have come across tutorials that demonstrate how to fade in elements when adding them to the bottom of a page, but I am looking for a way to achieve the same effect when adding elements to the top. ...

Is there a way for me to dynamically decide whether to use the append or prepend function?

Utilizing jQuery to retrieve data from the controller and populate a calendar represented by a table with days in columns. Implementing functionality for navigating between previous week / next week, as well as previous day / next day. The four scenarios s ...

The rule 'import/no-cycle' definition could not be located

After removing my npm package along with the package.lock.json file, I proceeded to run 'npm install' and followed up with 'npm update'. However, upon starting my application using 'npm run start', an error occurred. Upon lau ...

Steps to create a continuous blinking/flickering effect on a highchart pathfill

I am currently utilizing highcharts within one of my applications. I want to emphasize a particular stroke based on the content, and while I have achieved this already, I now need it to blink or flicker as if indicating an issue at that specific point. C ...

Incorporate JSON data using jQuery's AJAX in MVC3

I need assistance with parsing the JSON data retrieved from a webservice through my controller. Currently, I am displaying the entire JSON string in a div as text. However, I only want to extract specific values such as "color" and "size". I am unsure of ...

AngularJS is throwing an error because the current.$$route object is not defined

Having worked with AngularJS, I encountered an error when trying to set a title. Here is my App.js 'use strict'; var serviceBase = 'http://www.yiiangular.dev/' var spaApp = angular.module('spaApp', [ 'ngRoute' ...

What is the reason for the malfunction in the login dialog?

I'm having trouble implementing AJAX login functionality on my website. When I click the submit button, nothing seems to happen. Can someone take a look at the code and help me out? $(document).ready(function() { var user, pass; function login(us ...