Sam
Sam

Reputation: 14586

angularjs adding logic to ng-keydown

I'm using the ng-keydown directive for calling a search function when text in entered in an input box. I'd like to prevent the call to the search function if the search string length is less than 3.

I'm doing it this way:

 <input type="text" ng-keydown="filter()" ng-model="query">

and in the controller:

$scope.query;
$scope.filter = function () {
  if ($scope.query.length > 3)
    $scope.search()
}

Ok, that works, but is it possible to do the check for the search length directly in the attribute ng-keydown ?

Upvotes: 3

Views: 2674

Answers (1)

Langdon
Langdon

Reputation: 20053

Short answer: No.

Long answer: The ngKeydown directive is expecting an Angular Expression, not JavaScript. Angular Expressions do not support conditionals:

No Control Flow Statements

You cannot write a control flow statement in an expression. The reason behind this is core to the Angular philosophy that application logic should be in controllers, not in the view. If you need a conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead.

Upvotes: 6

Related Questions