javascript - 范围函数在使用 Angular 指令链接中不响应

标签 javascript angularjs

这是我的 html

<example-directive id="my_id" ng-blur="test()"></example-directive>

这是我的指令

app.directive('exampleDirective', function() {
  return {
    restrict: 'AE',
    scope: {
       label: "@",
    },
    template: '<span class="some_input"> <input required/></span>',
    controller: function($scope, $element){
    },
    link: function(scope, el, attr) {
     // this is not responsive when blur out
      scope.test = function(){
        console.log("what is up");
      }
     // this is responsive when blur out
     el.on('blur', function(){
      console.log("this is up");
       });
    }
  }
})

当我

$("#my_id").blur()

仅在控制台中

"this is up"

出现了

我不知道为什么当 example-directive 中发生模糊事件时我无法访问作用域函数

最佳答案

由于您在自定义元素上使用模糊事件,因此它不起作用。您需要在隔离范围内传递该元素,以便该指令可以通过在隔离范围内添加 blur: '&ngBlur' 来访问该方法。其中 blur 变量可以访问指定的 ngBlur 属性函数。

scope: {
   label: "@",
   blur: '&ngBlur'
},

然后您可以在指令 blur 事件中使用该事件

 el.on('blur', function(){
    console.log("this is up");
    //here we need to run digest cycle manually,
    //as we are dealing from outside angular context.
    $timeout(function(){ //include `$timeout` dependency in directive
        scope.blur();
    });
 });

关于javascript - 范围函数在使用 Angular 指令链接中不响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245188/

相关文章:

javascript - 仅在处理结果列表后才需要从 $http 查询返回数据

JavaScript:解析 bool

javascript - jQuery 一页滚动不起作用

AngularJS 未知提供程序 : $scopeProvider

javascript - 当使用 AngularJS 登录后授权 header 不存在时,Spring Security 不会抛出错误

javascript - 您存储返回回调的回调的模式是否有名称?

javascript - Angular 更新 $scope 变量在循环内

javascript - 如何预填充img父div的高度?

javascript - 当来源为 http 且目标 url 为 https 时,如何在本地网络中发出 POST 请求?

javascript - 如何在谷歌地图 api3 中用一条线连接两个标记