Search code examples
javascripthtmlangularjsdom-eventsangular-ui

Using ng-blur and ui-sref doesn't work as expected


I have a search field with a custom dropdown results panel which is shown when typing a word in it or when it is focused. So my html looks something like this:

<div class="input-group">
    <input type="text" class="form-control" ng-model="userSearch" ng-change="onInputChange()" ng-focus="onInputChange()" ng-blur="onInputBlur()" />
    <span class="input-group-btn">
        <button type="button" ng-click="search()">Search</button>
    </span>
</div>

<div id="results" ng-if="panelShown">
    <div ng-repeat="contact in contacts | filter: { name: userSearch }">
        <a ui-sref="profile({ id: contact.id })">{{ contact.name }}</a>
    </div>
</div>

The JavaScript is something like this:

app.controller("SearchController", ["$scope", function($scope) {
    $scope.contacts = [...];
    $scope.panelShown = false;

    $scope.onInputChange = function() {
        $scope.panelShown = true;
    };

    $scope.onInputBlur = function() {
        $scope.panelShown = false;
    };

    $scope.search = function() {
        // bla bla bla...
    };
}]);

So, as you can see, the structure of my $scope.contacts array data is this:

[
   {
       id: "1",
       name: "George"
   },
   {
       id: "2",
       name: "Adam"
   },
   {
       id: "3",
       name: "Ron"
   }
   ...
]

I want when the input is blurred to hide the panel with results (#results div) and when it's on focus again - to show it. This is working perfect actually.

The problem I'm having is when I click on some of the results, I'm not sent to the state from ui-sref (in the example - I must be redirected to the profile state). I'm guessing the blur event prevents from going on there, but I can't think of any solution for it.

Can someone help me with it?


Solution

  • This is because the blur event triggers before the click event that the ui-sref is bound to, so the button you are trying to click is hidden (and hence doesn't receive the click) by the time the click is registered.

    What you can do to solve this is use the ng-mousedown. The mousedown event triggers before a blur event, so it should solve your problem:

    app.controller("SearchController", function($scope, $state) {
      $scope.goToState = function (state, params) {
        $state.go(state, params);
      }
    }
    
    <a ng-mousedown="goToState('profile', {id: contact.id})">{{ contact.name }}</a>