2014-09-25 76 views
1

我希望我的控制器在用户单击表单域(当表单域获得焦点时)时执行某些操作。我怎样才能做到这一点?见this plunkerAngularJS:如何在表单域获得焦点时触发函数调用

这里是我的控制器: 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

您可以使用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

很多正确答案的,都在aprox的同时给予(我看不出谁是第一个),所以我会奖励你@meriadec对具有应答的演示,我不知道你可以在这里做到这一点在stackoverflow :) – EricC 2014-09-26 05:57:35

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

使用这样ng-focus

0

使用 - > NG-重点

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

this plunker

在他写的函数formFieldJustGotFocus()的代码,但它不是绑定到焦点事件

+0

请解释OP的代码有什么问题,以及为什么这通过编辑你的答案解决了问题*。 – 2014-09-25 13:04:50

相关问题