从指令生成的html中调用范围内的函数

Call function in scope from directive generated html?

本文关键字:调用 范围内 函数 html 指令      更新时间:2023-09-26

我做了一个指令,使用element.html()来设置html。在html代码中,我希望能够在指令使用的范围内调用函数。像这样:

app.directive('myDirective', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'A',
        link: function(scope, element) {
          element.html('<button ng-click="doit()">Does not work</button>');
        }
    };
}]);

doit()函数永远不会被调用。

我做了一个plnkr来演示:

http://plnkr.co/edit/nckqny1FNiJJjthmlSh8?p =预览

当你动态添加HTML时,你必须手动编译并使用$compile服务链接它:

app.directive('myDirective', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        link: function(scope, element) {
          var e = angular.element('<button ng-click="doit()">Works Now!!</button>');
          element.append(e);
          $compile(e)(scope);
        }
    };
}]);

为什么不只是一个模板呢?

return {
    restrict: 'A',
    template:'<button ng-click="doit()">Do It</button>',
    link: function(scope, element, attrs) {
    }
};

另一个方法是:

return {
  restrict: 'A',
  template: '<button>Brings up alert</button><br><button>Does not work</button>',
  link:function(scope, element, attrs){
    element.on('click', function(e){
      if(e.target.nodeName.toLowerCase() == 'button'){
        scope.doit();
      }
    });
  }
};

不像代码示例中那样内联地绑定click事件,你可以像上面那样在链接函数中绑定事件,但是你需要这样做:

  1. 在指令的返回中使用template:""选项
  2. 在你的链接函数中绑定事件。
  3. 当前元素是div本身,但是你必须在函数args中传递事件。
  4. 检查点击的目标是否为e.target.nodeName按钮
  5. e.target.nodeName结果tagName为大写,因此在上面的if条件中使用as。
  6. 如果点击的元素是button,执行scope.doit();