Why doesn't ng-click work when ng-blur used?
Asked Answered
B

1

10

I have used ng-click on div and it works as expected, but when I have used ng-blur on some other input, the ng-click on the div stops working.

Working code [addItem(item) is being called on click]

 <div ng-controller="TestController">
  <input type="text" ng-focus="show=true">
  <div ng-show="show" class="choosecont">
    Choose from selected
    <div ng-repeat="item in allItems" ng-click="addItem(item)" class="choose">{{item}}</div>
  </div>
  <div class="chosencont">
    Following are selected
    <div ng-repeat="item in selectedItems" class="chosen">{{item}}</div>
  </div>
</div>

Broken code [addItem(item) not being called]

 <div ng-controller="TestController">
  <input type="text" ng-focus="show=true" ng-blur="show=false">
  <div ng-show="show" class="choosecont">
    Choose from selected
    <div ng-repeat="item in allItems" ng-click="addItem(item)" class="choose">{{item}}</div>
  </div>
  <div class="chosencont">
    Following are selected
    <div ng-repeat="item in selectedItems" class="chosen">{{item}}</div>
  </div>
</div>

Related JS code

angular.module("myApp", [])
.controller("TestController", ["$scope", function($scope) {
  $scope.allItems = ["A", "B", "C", "D", "E"];
  $scope.selectedItems = [];
  $scope.addItem = function(item) {
    if ($scope.selectedItems.indexOf(item) == -1)
      $scope.selectedItems.push(item);
  }
}
]);

Here is plunkr http://plnkr.co/edit/eI5dvczO2E1Cp1SBPgQx?p=preview Click on input which will bring dropdown. Clicking on dropdown adds item to selected list in one case but not in other case.

I have tried to debug. scope is set correctly and it was accessible.

Bargain answered 17/3, 2015 at 13:23 Comment(1)
Basically your ng-blur executes before your ng-click. Check this SO answer, hope it helps. #25304760Mullet
H
17

The click event fires after blur, so the list is being hidden before you are able to click it. The simple solution is to use mousedown event instead of click:

ng-mousedown="addItem(item)"

Here is an update to your plunkr: http://plnkr.co/edit/sPGIb1afCayS1UiP73Q0?p=preview

Hummel answered 17/3, 2015 at 13:59 Comment(3)
Could you explain in your answer why the mousedown event is working and not the click ?Deland
Check out the answer I linked to: "The mousedown and blur events occur one after another when you press the mouse button, but click only occurs when you release it."Hummel
After ~5 years, you are the hero even I use Angular 8.Barkentine

© 2022 - 2024 — McMap. All rights reserved.