AngularJS:如何在表单字段获得焦点时触发函数调用

时间:2014-09-25 12:24:17

标签: angularjs

我希望我的控制器在用户单击表单字段时(表单字段获得焦点时)执行某些操作。我怎样才能做到这一点?请参阅this plunker

这是我的控制器: angular.module(' myApp',[])

.controller('AppCtrl', ['$scope',
  function($scope) {
    $scope.field1 = "Default text";
    $scope.focus = false;
    $scope.formFieldJustGotFocus = function() {
      $scope.focus = true; 
      // Do all the stuff I need to happen when the form has just gotten focus
    }
  }
]);

以下是观点:

<body ng-app="myApp" ng-controller="AppCtrl">
  <h3>Testing</h3>
  <p>I want to perform some action in the controller when a form field gets focus. How can I best achieve this?</p>
  <form name="myForm">
    <input type="text" name="field1" ng-model="field1">
  </form>
  <p>Form field has focus: {{focus}}</p>
</body>

4 个答案:

答案 0 :(得分:6)

您可以使用ngFocus指令。反之为ngBlur

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  
  <input type="text" ng-focus="isFocused = true" ng-blur="isFocused = false">
  <p ng-if="isFocused">Focus !</p>
  
</div>

答案 1 :(得分:0)

<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus()">

像这样使用ng-focus

答案 2 :(得分:0)

使用 - &gt; NG-聚焦

<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus();">

this plunker

在代码中他编写了函数formFieldJustGotFocus(),但它没有绑定到焦点事件

答案 3 :(得分:0)

尝试ng-focus

查看更多信息: https://docs.angularjs.org/api/ng/directive/ngFocus