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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
hridayesh
  • 1,123
  • 1
  • 14
  • 36
  • Basically your ng-blur executes before your ng-click. Check this SO answer, hope it helps. http://stackoverflow.com/questions/25304260/angular-manipulating-event-firing-order-namely-ng-blur-ng-click – jarz Mar 17 '15 at 13:59

1 Answers1

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

Community
  • 1
  • 1
j.wittwer
  • 9,497
  • 3
  • 30
  • 32
  • Could you explain in your answer why the `mousedown` event is working and not the `click` ? – RPDeshaies Apr 08 '16 at 13:16
  • 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." – j.wittwer Apr 08 '16 at 13:20
  • 1
    After ~5 years, you are the hero even I use Angular 8. – canmustu Apr 22 '20 at 15:51