2

I'm searching for a angular-way to attach a global focus event to all input fields that appear on my site, and will appear in the future. With jQuery, I would have used the live method, and simply put the event handler in the index.html.

I need to listen to the focus and blur event, because of a bug when the virtual keyboard on iOS 7 in mobile Safari appears. After I received the event, I have to re-position a navigation bar at the bottom (see here for the bug iOS 5 fixed positioning and virtual keyboard).

So, what is the best Angular-way to achieve this, without injecting something into controllers all the time? Is there a "global-way"?

Community
  • 1
  • 1
23tux
  • 14,104
  • 15
  • 88
  • 187

1 Answers1

2

I would use a directive to capture the focus/blur something like this:

.directive('onFocusBlur',function() {
    return {
        restrict : 'A', 
        link : function($scope,$element,$attr) {
            $element.bind('focus',function() {
                $scope[$attr.onFocusBlur] = true;
            });
            $element.bind('blur',function() {
                $scope[$attr.onFocusBlur] = false;
            });
        }
    }
})

<!-- my focus/blur input -->
<input on-focus-blur="respoitionMyNav" />

<!-- my nav -->
<div ng-class="{ reposition-class : respoitionMyNav }">
</div>
koolunix
  • 1,995
  • 16
  • 25
  • Thanks for your answer. But for this, I have to manually put the `on-focus-blur` to all input fields. Is there a way to handle this automatically? – 23tux Mar 11 '14 at 19:23
  • Because of the declarative nature of Angular there's not a way to do this, as you would with a jquery selector string. I have never found this to be an issue. If you can post your markup I might be to advise more on how to best do this – koolunix Mar 11 '14 at 20:37
  • Ok, I see. But I have some problems with the scope: The blur event fires for my input elements, but `$scope` refers to the input element, not to the scope of my navigation (they are in different scopes). How could I solve this? – 23tux Mar 12 '14 at 11:07
  • In that case I would use the Angular messaging. From the directive: "$scope.$emit('onFocusBlurEvent',[true or false])", and from the other controller $rootScope.$on('onFocusBlurEvent',function(e,show) { if(show) ...}); – koolunix Mar 12 '14 at 15:43