0

I want to call an event when focusing each element.

However I think it is not good to set an ngFocus directive on each element as there can be many of them.

How can I add an on focus event handler to each element at runtime?

Plunkr

<ng-form name="myForm">
    <p><label>name1: </label><input type="text" name="name1" ng-focus="onFieldFocus(myForm, 'name1')"/></p>
    <p><label>name2: </label><input type="text" name="name2" ng-focus="onFieldFocus(myForm, 'name2')"/></p>
</ng-form>

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.name1 = 'text1 here';
  $scope.name2 = 'text2 here';

  $scope.result = "Nothing";

  $scope.onFieldFocus = function (_formCtrl, _fieldName) {
    $scope.result = "field "+_fieldName+" of form "+_formCtrl.$name+" was focused"; 
  }
});

I would like to use angular.element and $scope.myForm with a a for..each through myForm elements not starting with $, something similar to this:

  for (var i in $scope.myForm) {
    console.log(i);
    $scope.result += "1";
    if ($scope.myForm.hasOwnProperty(i)) {
      var property = $scope.myForm.i;
      if(property.charAt(0) != '$') {
        $scope.result += property+", ";
      }
    }
  }
Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87

1 Answers1

1

I would argue that it is good to set ngFocus on each element. AngularJS is declarative, so you want to explicitly declare behavior on relevant elements, rather than imperatively setting it somewhere else.

If you don't want to repeat yourself by putting the ngFocus directive on each form element, then I would create a directive (call it onFieldFocus or something) that you apply to the ngForm element. The behavior of the directive would be to apply the ngFocus directive to each input that is a descendant of the form.

John Bledsoe
  • 17,142
  • 5
  • 42
  • 59
  • Thank you for your answer. May be it is much more better idea, then mine (to add directive to form), but it is still question how to send event listener. I know, how to create directive, but in it I'll still use same `for..each` with same problem - how to add focus listener. – Sharikov Vladislav Nov 04 '14 at 14:28
  • Don't use the same for...each. Just the directive element in the link function to find decendent input elements and directly add the ngFocus directive to them. Those descendant elements haven't been linked yet so the ngFocus directive should work. – John Bledsoe Nov 04 '14 at 14:47
  • Yes yes yes. `directly add the ngFocus` – I don't understand how to directly add the ngFocus. How? [This guy](https://www.google.ru/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#newwindow=1&q=directly+add+the+ngFocus+angular) don't help me or my answer is not correct. I need `for..each` to find and point each input. Or nope? – Sharikov Vladislav Nov 04 '14 at 14:52