最近我在做一个angular js项目。我碰巧遇到需要处理焦点和模糊事件文本框的情况。我的情况是,当焦点离开文本框时我需要附加 $ 符号,而当文本框获得焦点时我需要附加 $。
我试图为此创建组件
angular.module('myApp').component('dollarText', {
templateUrl: '<input type="text">',
controller: function($scope, iElm, iAttrs){
iElm.bind('change', function(){
iElm.val('$'+iElm.val());
});
}
});
但我无法访问焦点事件。我知道我做的不对。 如何在 Angular 分量中同时触发焦点和模糊。 Angular 组件是我任务的最佳选择。
最佳答案
如果你想处理某个 div
或其他,例如,在 ng-repeat
或在一长串元素中,你需要使用 function(this)
并且在 JavaScript 方面,您需要使用 function(context)
与该元素进行交互。
Here's a working Plunker我认为您正在寻找的东西。
HTML:
<html ng-app="myApp">
<body ng-controller="myController">
<!--When on-blur, call blur(this), when on-focus, call focus(this)-->
<input type="text" name="myApplicationRocks"
ng-focus="focus(this)" ng-blur="blur(this)"/>
<!-- Content changes on blur and on focus-->
<h1>{{whatToWrite}}</h1>
</body>
</html>
JS:
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope){
$scope.whatToWrite = "Well, try something";
$scope.focus = function(context){
console.log("On Focus");
context.whatToWrite = "Focus On!";
};
$scope.blur = function(context){
console.log("On Blur");
context.whatToWrite = "Blur On!";
};
});
当然它也可以在没有 this
和 context
的情况下工作,但在某些情况下它非常有用。
希望我对您有所帮助。
关于javascript - 在 Angular 1.5 组件中处理焦点和模糊事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37500677/