Sharikov Vladislav
Sharikov Vladislav

Reputation: 7269

How to set ngFocus directive on element at runtime?

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+", ";
      }
    }
  }

Upvotes: 0

Views: 450

Answers (1)

John Bledsoe
John Bledsoe

Reputation: 17642

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.

Upvotes: 1

Related Questions