hridayesh
hridayesh

Reputation: 1143

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

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.

Upvotes: 10

Views: 6379

Answers (1)

j.wittwer
j.wittwer

Reputation: 9497

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

Upvotes: 17

Related Questions