javascript - 在 Angular 1.5 组件中处理焦点和模糊事件

标签 javascript angularjs angularjs-directive

最近我在做一个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!";
  };
});

当然它也可以在没有 thiscontext 的情况下工作,但在某些情况下它非常有用。

希望我对您有所帮助。

关于javascript - 在 Angular 1.5 组件中处理焦点和模糊事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37500677/

相关文章:

javascript - 将常量值赋给变量

javascript - 如何在 key 来自页面本身的 View 中呈现哈希?

解析对象时AngularJS插值错误

javascript - 无法解析 JSON 字符串

javascript - 查找方法(不是 queryBuilder)的嵌套 AND 和 OR 条件

javascript - 将 angulajs UI-Select 绑定(bind)到 UI-Grid 过滤器

mysql - $scope 在 app.js 文件中不起作用。但是当 HTML 文件包含 app.js 文件的内容时 $scope 起作用

javascript - window.location.href/reload 导致 AngularJS [$rootScope :infdig] 10 $digest() iterations reached

javascript - 同一页面上多次自定义指令需要相同的数据

angularjs - 如何在指令模板中使用范围