krynio krynio - 6 months ago 84
Javascript Question

Angular ng-click not fired when ng-blur added

I try to combine ng-click and ng-blur but it causes error, ng-click is not fired.

I have input and below I have list of options which I show when input is focused.

<div ng-app="myApp" ng-controller="MyCtrl">
<input type="text"
ng-model="value"
ng-focus="onFocus()"
ng-blur="onBlur()"
>
<ul ng-show="visible">
<li ng-repeat="i in items" ng-click="setValue(i)">{{i}}</li>
</ul>
</div>


On items on list I defined ng-click. It set new value in model.
It works, but when I add function which hide options on input blur new value is not updated.

Here is my js code:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
$scope.visible = false;
$scope.items = ["Foo", "Bar", "Baz"];
$scope.onFocus = function() {$scope.visible = true;};
$scope.onBlur = function() {$scope.visible = false;};
$scope.setValue = function(value) { $scope.value = value; };
}

myApp.controller('MyCtrl', MyCtrl)


Here is full sample:
https://jsfiddle.net/uqs19rea/

M4N M4N
Answer

This is because the blur event happens before the click event, which means the list items are already hidden when the click happens.

You can delay the hiding of the list, e.g. by using angular's $timout service:

function MyCtrl($scope, $timeout) {
    $scope.visible = false;
    $scope.items = ["Foo", "Bar", "Baz"];
    $scope.onFocus = function() {$scope.visible = true;};
    $scope.onBlur = function() {
        $timeout(function() {$scope.visible = false;}, 200);
    };
    $scope.setValue = function(value) { $scope.value = value; };
}

See the uppdated sample: https://jsfiddle.net/uqs19rea/1/

Comments