【问题标题】:How to delegate ngFocus/ngBlur to directive's template <input> element?如何将 ngFocus/ngBlur 委托给指令的模板 <input> 元素?
【发布时间】:2015-11-04 01:18:52
【问题描述】:

我正在尝试创建一个自定义组件(指令),它由一个 &lt;input&gt; 框和一个 [-][+] 按钮组成。目前,下面的例子只实现了输入框。

所以,假设我的指令有以下 HTML:

&lt;my-input ng-blur="onBlur($event)" ng-focus="onFocus($event)"&gt;&lt;/my-input&gt;

出于测试目的,我使用以下代码:

app.run(function ($rootScope) {
  $rootScope.onBlur = function ($event) {
    console.log('onBlur', $event);
  };

  $rootScope.onFocus = function ($event) {
    console.log('onFocus', $event);
  };
});

现在我想创建我的自定义 &lt;my-input&gt; 指令,它在模板上有一个 &lt;input&gt; 框,我需要在 &lt;my-input&gt; 上设置 ng-blurng-focus 来响应输入上的模糊/焦点事件盒子。

我有以下解决方案几乎工作:http://codepen.io/anon/pen/KpELmj

1) 我感觉这可以通过更好的方式实现,但我似乎做不到。想法?

2) $event 似乎是 undefined 我不明白为什么。想法?

【问题讨论】:

    标签: angularjs angular-directive inputbox dom-events


    【解决方案1】:

    好的,想通了。多伦的回答是一个很好的研究起点,但现在我想我已经找到了你想要的东西。关键是你必须在链接部分使用&amp; 才能让它执行表达式。

    .directive('myInput', function($timeout) {
        return {
            restrict: 'E',
            scope: {
                data: '=',
                blur: '&myBlur' //this is the key line
            },
            template: '<input ng-blur="blur($event)" ng-model="data">'
        }
    })
    

    这是你使用它的方式:

    <my-input my-blur="runBlurFunc()"></my-input>
    

    如果你真的想在根作用域上定义函数,可以使用$scope.$root.onBlur()代替runBlurFunc()

    【讨论】:

      【解决方案2】:

      希望我没听错你的问题,你尝试过使用链接功能吗?

      app.directive('myInput', function () {
        return {
          restrict: 'E',
          scope: {
            ngBlur: '&',
            ngFocus: '&'
          },
          bindToController: true,
          controller: controllerFn,
          controllerAs: 'ctrl',
          link:function(scope){
      
            scope.onBlur = function(ev){
              console.log(ev);
            }
      
            scope.onFocus = function(ev){
             console.log(ev);
           }
      
         },
      
         template: '[-]<input ng-blur="onBlur($event)" ng-focus="onFocus($event)"></input>[+]'
       }
      });
      

      【讨论】:

      • 恐怕你没有,也许我没有正确解释自己。使用您的解决方案,您将 console.logs 移动到指令实现,我需要在该范围之外。我以run 块和$rootScope 为例,但它也可以是其他一些控制器。基本上,我想将 ng-focusng-blur 事件委托给指令父范围。
      猜你喜欢
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2015-11-02
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多