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

自古美人都是妖i 提交于 2020-01-04 04:25:18

问题


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? Thanks in advance!


回答1:


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>


来源:https://stackoverflow.com/questions/27514036/using-ng-blur-and-ui-sref-doesnt-work-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!