0

I'm currently trying to "save" all the content in a webpage after a piece is edited. IE, a user clicks into an input, enters some data, and as soon as he/she clicks elsewhere I want to run a function to gather all the model data and save it in browser local storage.

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

That's the normal way of doing it, but let's say i have tons of inputs:

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

is there anything I can do to apply the ng-blur effect to all inputs of a page or must I put ng-blur attribute into every input?

Kenny
  • 2,124
  • 3
  • 33
  • 63
  • Use ng-model on each and assign their values to an object and set a watch on the object in your controller. – John Halbert Jun 29 '16 at 18:20
  • @JohnHalbert actually I have most inputs as ``. So I can watch this model change from the controller? – Kenny Jun 29 '16 at 18:22

2 Answers2

0

You could create a custom directive to do that. This is an adaptation from this question's answer:

AngularJS 1.3 - `ng-change`-like functionality for the entire form

Haven't tested this, but it should get you on the right track.

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

and to use it:

<form inputs-on-blur="doSomething()">
   <input />
   <input />
   <input />
</form>
Community
  • 1
  • 1
DerekMT12
  • 1,329
  • 11
  • 15
  • Thanks so much for the feedback! Will this also work by putting `inputs-on-blur` in a regular `div` that's a container for all inputs? As I'm not using a form, just the input tag. – Kenny Jun 29 '16 at 18:14
  • Great, I'll try it out soon. Thank you! – Kenny Jun 29 '16 at 18:15
0

of course it's possible. You need to dynamically add data-ng-blur to input tag. The code in your controller should be :

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

Jack Wang
  • 462
  • 7
  • 17
  • So this basically just programmatically puts `ng-blur` into all the `inputs` for me, right? – Kenny Jun 29 '16 at 18:20
  • Yes, it will apply `data-ng-blur` to all the inputs in your page. If you want to specify which kind of input should `ng-blur` attach to, you can use `document.querySelectorAll('input[type="text"')` instead. – Jack Wang Jun 29 '16 at 18:26