3

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>

4 Answers 4

8

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Lots of correct answers, all given at aprox the same time (I cannot see who was first), so I'll award you @meriadec for having in-answer demo, I had no idea that you could do that here at stackoverflow :)
0
<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus()">

use like this ng-focus

Comments

0

Try ng-focus.

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

Comments

0

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

1 Comment

Please explain what is wrong with OP's code and why this solved the problem by editing your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.