0

I am new to angular and I am trying to write a reusable directive to set focus on elements inside some parent.

<div class="products" ng-controller="productsController" id="products" > Name <input type="text" ng-model="name" tabindex="1" focus-element /> Price <input type="text" ng-model="price" tabindex="2" focus-element /> </div> .directive('focusElement', function () { return { restrict: 'A', link: function($scope, $element, attrs) { var fE = function() { if ($element[0].value === '') { var elms = document.getElementsByTagName('body')[0].getElementsByTagName("input"); var alredyFocused = false; for (var i = 0; i < elms.length; i++) { if (elms[i].value === '' && Number(elms[i].getAttribute("tabindex")) < attrs.tabindex) { alredyFocused = true; continue; } } if (!alredyFocused) { $element[0].focus(); } } } fE(); //...some other logic } } }); 

In this code I am looking for input elements inside the whole body which is wrong. How can I restrict a directive to a parent div(controller) if I want a directive to be reusable (Id or class or html inside a div will be different from div to div) ?

I have tried to write a directive for the div itself in order to set focus on the first of its children which has no value but in this case I cannot use ng-model of each input element in order to track model changes (using $scope.$watch("?ngModule attribute from an input which is many?", function () {})).

1 Answer 1

0

Why not write a simpler directive that takes a callback function and calls it when the element gets focus. Something like:

.directive('myDirective', function(){ return { scope: { callback: '&' }, link: function (scope, element) { element.bind('focus', function() { scope.$apply(scope.callback()); }); } } }); 

The directive doesn't need to know what the callback is doing only that it needs to be called on focus. This can be applied to all elements that require some behavior on focus.

http://jsfiddle.net/b6ww0rx8/11/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, but I need to set focus on any input that is empty (has no value), not to do something when an element gets focus. Sorry for the not clear explanation of the problem, I have edited the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.