0

Fairly new to javascript. I was wondering with the following tag, besides having to manually put in Ids, is there a way to set .focus() to the container (custom directive)?

<tile class="ng-scope gridster-item" tilevalue="1" gridster-item="tile" row="0" col = "0" ng-repeat="tile in selectedTiles"> </tile>
KO12
  • 215
  • 1
  • 3
  • 10
  • Possible duplicate of [How to set focus on input field?](http://stackoverflow.com/questions/14833326/how-to-set-focus-on-input-field) – Alon Eitan May 27 '16 at 19:32
  • You can define a value attr and a focus variable to define how value is selected. And then, when the focus variable changes, you can to compare with special value field and set focus. Don't forget of $timeout – Joao Polo May 27 '16 at 21:05

1 Answers1

0

Yes you can create a custom directive and add focus event on that element. Below i had create a custom directive "custom-on-focus" with focus and blur event attached on that directive.

Here goes your template

<div ng-init="selectedTiles=[1,2,3,4,5]">
    <input type="text" custom-on-focus ng-repeat="tile in selectedTiles"/>
</div>

Here is the custom directive code

<script>
angular.module('demoApp')
    .directive('customOnFocus',[function(){
    return {
        restrict : 'A',
        link : function (scope,element,attrs) {

            var targetElem = element[0];

            targetElem.addEventListener("focus", focusHandler);

            targetElem.addEventListener("blur", blurHandler);

            function focusHandler(event) {
                // THINGS TO DO ON FOCUS
                // for example i am changing background color
                event.target.style.background = "pink";
            }

            function blurHandler(event) {
                //THINGS TO DO ON BLUR
                // reseting background color
                event.target.style.background = "white";
            }

            // Its very important to remove these events listener 
            // on scope destruction else it will cause memory leaks

            scope.$on('$destroy',function(){
                targetElem.removeEventListener('focus',focusHandler);
                targetElem.removeEventListener('blur',blurHandler);
            })

        }
    }
}]);