EricC
EricC

Reputation: 5870

AngularJS: How to trigger function call when a form field gets focus

I want my controller to perform some action when a user clicks in a form field (when the form field gets focus). How can I do this? See this plunker.

Here is my controller: 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
    }
  }
]);

And here is the view:

<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>

Upvotes: 3

Views: 12715

Answers (4)

abdullacm
abdullacm

Reputation: 636

use -> ng-focus

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

this plunker

in the code he had written the function formFieldJustGotFocus(), but it was not bound to the focus event

Upvotes: 0

Taras Kostiuk
Taras Kostiuk

Reputation: 211

Try ng-focus.

See more info: https://docs.angularjs.org/api/ng/directive/ngFocus

Upvotes: 0

meriadec
meriadec

Reputation: 2983

You can use the ngFocus directive. The inverse is 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>

Upvotes: 8

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

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

use like this ng-focus

Upvotes: 0

Related Questions