2014-09-02 87 views
30

我使用angularjs和我创建了一个正常输入领域是这样的:Angularjs输入字段焦点事件?

<input type="text" style="border: none" ng-model="model" > 

我要做到以下几点:

,如果有人点击输入字段,我想呼吁例如方法A,然后他在该字段中写入文本,并且如果用户在我的页面中的某处单击以使输入字段不再集中,它应该调用方法B.这是否可以使用angularjs?如果是的话,我该怎么做? ng-focus仅在输入事件处于活动状态,但不在输出处。

我想用此方法锁定某些方法,方法A只将值设置为true,方法B将相同的值设置为false。但我必须知道什么时候输入字段是活动的,什么时候没有。

回答

47

您正在查看ng-focusng-blur

<input type="text" style="border: none" ng-model="model" ng-focus="A()" ng-blur="B()"> 

在一个侧面说明,使用CSS类,而不是内嵌样式.. :)

或者只需要调用与参数相同的方法和设置的值ACC: -

<input type="text" style="border: none" ng-model="model" ng-focus="A(true)" ng-blur="A(false)"> 
+1

http://plnkr.co/edit/Wo0Lp0?p=preview – PSL 2014-09-02 22:18:14

3

你可以B法结合至角的纳克模糊指令以检测当输入失去焦点

<input type='text' ng-focus='methodA()' ng-blur='methodB()' ng-model='model'> 
5

如果您正在使用您可能希望应用于整个应用程序中的字段的功能,则可以将其置于指令中。 这里是添加和删除根据场上的焦点或模糊的CSS类的例子:

angular.module('myApp').directive('inputFocus', function() { 

var FOCUS_CLASS = 'input-focused'; 
return { 
    restrict: 'A', 
    priority: 1, 
    require: 'ngModel', 
    link: function (scope, element, attrs, ctrl) { 
    element.bind('focus',function() { 
     element.parent().addClass(FOCUS_CLASS);  
    }).bind('blur', function() { 
     element.parent().removeClass(FOCUS_CLASS); 
    }); 
    } 
}; 
}); 
+0

尼斯和整洁的 - 你可以也可以使用来自jQuery的'element.focus()'和'element.blur()',因为这会让它更整洁一些。 – Boris 2016-03-01 10:41:54