简体   繁体   English

angularjs为ng-keydown添加逻辑

[英]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. 我正在使用ng-keydown指令在输入框中输入文本时调用搜索功能。 I'd like to prevent the call to the search function if the search string length is less than 3. 如果搜索字符串长度小于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 ? 好的,这有效,但是可以直接在属性ng-keydown中检查搜索长度吗?

Short answer: No. 简答:不。

Long answer: The ngKeydown directive is expecting an Angular Expression , not JavaScript. 答案很长: ngKeydown指令期待一个Angular Expression ,而不是JavaScript。 Angular Expressions do not support conditionals: Angular Expressions不支持条件:

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. 这背后的原因是Angular哲学的核心,即应用程序逻辑应该在控制器中,而不是在视图中。 If you need a conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. 如果需要条件,循环或从视图表达式抛出,请委托JavaScript方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM