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 () {})).